我有一个包含 todolists 字段的用户模型,在 todolists 字段中我想通过 id 获取特定的 todolist。我的查询是这样的:
User.find({_id: user._id, _creator: user, todoList: todoList._id}, 'todoLists') // how do I query for todoList id here? I used _creator this on populate query.
我也可以像这样对 Usermodel 字段进行搜索吗?
User.todoLists.find({todoList: todoList._id})
我还没有测试过这个,因为我仍在修改我的 Graphql 架构,而且我是 mongoose 的新手。我非常感谢链接和建议。帮忙?
最佳答案
假设您的模型如下所示:
const todoListSchema = new Schema({
item: { type: String },
}, { collection: 'todolist' });
const userSchema = new Schema({
todoList: [todoListSchema],
}, { collection: 'user' });
mongoose.model('user', userSchema);
mongoose.model('todoList', todoListSchema);
现在您有多种方法可以做到这一点:
<强>1。使用数组filter()方法 reference
User.findById(_id, (err, user) => {
const todoList = user.todoList.filter(id => id.equals(tdlId));
//your code..
})
<强>2。使用 mongoose id() 方法 reference
User.findById(_id, (err, user) => {
const todoList = user.todoList.id(tdlId);
//your code..
})
<强>3。使用 Mongoose 聚合 reference
User.aggregate(
{ $match: { _id: userId} },
{ $unwind: '$todoList' },
{ $match: { todoList: tdlId } },
{ $project: { todoList: 1 } }
).then((user, err) => {
//your code..
}
});
关于node.js - 如何在 Mongoose 中进行嵌套查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44208202/