首页 > 解决方案 > 如何使用 Mongoose 在 mongoDB 中填充 3 个集合

问题描述

我有三个集合,例如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文档(完成)和相关user文档(我想要的)?

像这样的通缉查询

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

标签: node.jsmongodbmongoosemongodb-queryaggregation-framework

解决方案


您可以使用$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' }}])

两者都会给你相同的结果


推荐阅读