Node.js 如何在猫鼬中进行嵌套查找?
我有一个用户模型,其中包含todolist字段,在todolist字段中,我希望通过id获取特定的todolist。我的查询如下:Node.js 如何在猫鼬中进行嵌套查找?,node.js,mongoose,Node.js,Mongoose,我有一个用户模型,其中包含todolist字段,在todolist字段中,我希望通过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.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。使用数组筛选器()方法
2。使用mongoose id()方法
3。使用mongoose聚合
能否将用户架构定义添加到问题中?不,不能。上面的查询将返回一个用户对象。如果你想得到todolist本身,你必须使用聚合框架,我只是在读mongoose文档。mongodb文档帮了大忙。我想做猫鼬的工作,而不是执行任何js。谢谢,我使用数字2是因为它的特殊性。但如果您能告诉我您在使用什么和建议,我将不胜感激。我使用的是聚合框架。我相信你可以通过以上所有的选择来实现你的目标。使用聚合框架对我来说更容易,也更直观。使用1或2可以更容易地使用编程语言(如js)操作数据。
User.findById(_id, (err, user) => {
const todoList = user.todoList.filter(id => id.equals(tdlId));
//your code..
})
User.findById(_id, (err, user) => {
const todoList = user.todoList.id(tdlId);
//your code..
})
User.aggregate(
{ $match: { _id: userId} },
{ $unwind: '$todoList' },
{ $match: { todoList: tdlId } },
{ $project: { todoList: 1 } }
).then((user, err) => {
//your code..
}
});