NodeJS:如何使用 MongoDB 获取具有可变子属性的对象?
NodeJS: How to get objects with variable child properties with MongoDB?
我正在尝试获取子 属性 为 true
的文档数组。这是一些代码:
public static getTeams(req, res) {
// Initialize a connection to the database
Globals.initDb(res).then((db: Db) => {
// Reference a collection in the Database
db.collection('teams', (error: Error, collection: Collection) => {
// Check if an error occured getting the collection
Globals.checkError({ error, result: collection, res }).then(() => {
// find teams that a user administrates
collection.find(
{ 'usergroups.users': { [req.params.id]: true } },
{ name: 1, icon: 1, type: 1, thumbnail: 1 }
).toArray((err, teams: Array<{ name: string, icon: string }>) => {
// make sure that went through OK
Globals.checkError({ error: err, result: teams, res }).then(() => {
if (!teams[0]) {
teams = [];
}
res.status(200).json(teams);
});
});
});
});
});
}
checkError
只是我为了方便查错而写的一个函数,效果很好,我查过了。我正在尝试访问 usergroups.users.#userId#
为真的一组团队。因此,如果您的 ID 是 j4k53,则 usergroups.users.j4k53
为真。
但是,当多个ID为真时,不返回文档。例如,如果 j4k53
和 lfk3m
都为真,则它们都不返回。
感谢您的帮助。 (这是打字稿的节点,所以如果你不熟悉 TS,它可能看起来有点时髦)。
知道了:可以这样写:
{ ['usergroups.users.' + req.params.id]: true}
祝所有觉得有用的人好运!
我正在尝试获取子 属性 为 true
的文档数组。这是一些代码:
public static getTeams(req, res) {
// Initialize a connection to the database
Globals.initDb(res).then((db: Db) => {
// Reference a collection in the Database
db.collection('teams', (error: Error, collection: Collection) => {
// Check if an error occured getting the collection
Globals.checkError({ error, result: collection, res }).then(() => {
// find teams that a user administrates
collection.find(
{ 'usergroups.users': { [req.params.id]: true } },
{ name: 1, icon: 1, type: 1, thumbnail: 1 }
).toArray((err, teams: Array<{ name: string, icon: string }>) => {
// make sure that went through OK
Globals.checkError({ error: err, result: teams, res }).then(() => {
if (!teams[0]) {
teams = [];
}
res.status(200).json(teams);
});
});
});
});
});
}
checkError
只是我为了方便查错而写的一个函数,效果很好,我查过了。我正在尝试访问 usergroups.users.#userId#
为真的一组团队。因此,如果您的 ID 是 j4k53,则 usergroups.users.j4k53
为真。
但是,当多个ID为真时,不返回文档。例如,如果 j4k53
和 lfk3m
都为真,则它们都不返回。
感谢您的帮助。 (这是打字稿的节点,所以如果你不熟悉 TS,它可能看起来有点时髦)。
知道了:可以这样写:
{ ['usergroups.users.' + req.params.id]: true}
祝所有觉得有用的人好运!