如何在mongoose中嵌套查找?

我有一个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字段上进行search吗?

 User.todoLists.find({todoList: todoList._id}) 

我还没有testing过,因为我仍然在修改我的Graphql模式,我是mongoose新。我真的很感激链接和build议。 帮帮我?

假设你的模型是这样的:

 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()方法的 引用

 User.findById(_id, (err, user) => { const todoList = user.todoList.filter(id => id.equals(tdlId)); //your code.. }) 

2.使用mongoose id()方法的 引用

 User.findById(_id, (err, user) => { const todoList = user.todoList.id(tdlId); //your code.. }) 

3.使用mongoose聚合 参考

 User.aggregate( { $match: { _id: userId} }, { $unwind: '$todoList' }, { $match: { todoList: tdlId } }, { $project: { todoList: 1 } } ).then((user, err) => { //your code.. } });