node.js - 如何在 Mongoose 中进行嵌套查找?

标签 node.js 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 字段进行搜索吗?

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/

相关文章:

node.js - Model.find() 在 Mongoose 中返回空

node.js - 我可以从 Socket.io 访问 cookie 吗?

javascript - Nodejs 和 Mongoose 数据获取

java - 在 DOM 中使用 mongodb 对象的 _id 值是个好主意吗?

node.js - 在 Alpine docker 中找不到 Node

node.js - Mongoose Schema 设置过期字段来删除文档?

node.js - 数组内部数组的架构?

javascript - 如何更改 Mongoose 中文档子数组的对象内的 bool 值?

node.js - 如何从 Firebase 函数中的 TIMESTAMP 获取字符串和日期对象?

javascript - Node.JS Joi 对未知对象抛出错误