node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我有三个集合,例如 UserProgram 和 `Agenda。这些模型如下。

用户模型

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
    name: {type:String},
    email: {type:String}
},{timestamps:true
}
);

module.exports = mongoose.model('User', UserSchema);

程序模型

const mongoose = require('mongoose');

const NoteSchema = mongoose.Schema({
    name: {type:String},
    timefrom: {type:Date},
    timeto: {type:Date},
    status: {type:String},
    venue: {type:String},
    timetype: {type:Number},
    userid:{type:mongoose.Schema.Types.ObjectId,ref : 'User', required: true},
    logo :{type:String,default: 'programe'}
},{timestamps:true
});

module.exports = mongoose.model('Program', NoteSchema);

议程模型

const mongoose = require('mongoose');

const AgendaSchema = mongoose.Schema({
    name: {type:String},
    timefrom: {type:Date},
    timeto: {type:Date},
    status: {type:String},
    proorder: {type:String},
    proid:{type:mongoose.Schema.Types.ObjectId,ref : 'Program', required: true}
},
{timestamps:true}
);

module.exports = mongoose.model('Agenda', AgendaSchema);

现在我只获取议程和程序数据。

议程控制者

// Retrieve and return all agenda from the database.
exports.findAll = (req, res) => {

    Agenda.find()
    .populate('proid')
    //.populate('userid')

    .then(agendas => {
        res.send(agendas);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occurred while retrieving agenda."
        });
    });
};

当我转到此 URL 和 GET 方法时,我想填充 agenda 文档(完成)、相关的 program 文档(完成)和相关的用户文档(这个我要)?

像这样的查询

SELECT * 
FROM users, programs, agendas
WHERE agendas.proid = programs.id AND programs.userid = users.id

最佳答案

您可以使用 $lookup聚合

Agenda.aggregate([
  { "$lookup": {
    "from": Program.collection.name,
    "let": { "proid": "$proid" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$_id", "$$proid" ] } } },
      { "$lookup": {
        "from": User.collection.name,
        "let": { "userid": "$userid" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$userid" ] } } },
        ],
        "as": "userid"
      }},
      { "$unwind": "$userid" }
    ],
    "as": "proid"
  }},
  { "$unwind": "$proid" }
])

或者填充

Agenda.find()
  .populate([{ path: 'proid', populate: { path: 'userid' }}])

两者都会给你相同的结果

关于node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51724786/

相关文章:

node.js - 彻底关闭 express.js + mongodb 服务器(使用 node.js)

mongodb - 连接到 MongoDB Atlas Cluster 错误

javascript - 使用 Mongoose 查找或创建

node.js - 如何增加 Ionic 的 Javascript 堆大小

iOS 未使用 apn nodejs 接收后台推送通知

java - spring 的 mongo db 身份验证错误(查询失败,错误代码 13 和错误消息)

node.js - 如何用mongoose实现分页和总计

javascript - Discord 机器人正在运行两个实例,我找不到其中一个来将其关闭

javascript - 如何删除/停止在 jquery 中执行的脚本

node.js - 如何在另一个文件夹中使用我的主应用程序文件夹中的 Mongoose 模型?