【问题标题】:How to populate multiple tables in mongodb to display in ejs?如何在 mongodb 中填充多个表以在 ejs 中显示?
【发布时间】:2021-09-26 13:59:53
【问题描述】:

我创建了三个模式。这里,动物模式引用物种模式,物种模式引用特殊信息模式。

var animal = new mongoose.Schema({
name:String,
info:String,
species:[{
    type:mongoose.Schema.Types.ObjectId,
    ref:species
}]
});



var species = new mongoose.Schema({
name:String,
sound:String,
speicalinfo:[{
    type:mongoose.Schema.Types.ObjectId,
    ref:specialinfo
}]
});


var specialinfo = new mongoose.Schema({
history:String,
speciafeature:[]
});

我想填充动物模式,以便我也可以访问特殊信息数据。

这是我对索引页面的获取请求函数。

app.get('/index', (req,res)=>{
animal.findById(id).populate('species').exec(function (err, animal) {
    if (err) {return handleError(err);}
    res.render('index',{
    animal: animal
   });
  });
})

我想从索引页面访问特殊信息模式的历史和特殊功能字段。我怎样才能做到这一点? 谢谢!

【问题讨论】:

    标签: node.js mongodb ejs


    【解决方案1】:

    猫鼬自动填充

    您可以使用 'mongoose-autopopulate' 并获取自动填充的数据,然后您可以填充物种

    npm i mongoose-autopopulate

    https://www.npmjs.com/package/mongoose-autopopulate

    import mongooseAutopopulate from 'mongoose-autopopulate';
    
    var animalSchema = new mongoose.Schema({
        name: String,
        info: String,
        species: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: species,
            autopopulate: true
        }]
     );
    
    animalSchema.plugin(mongooseAutopopulate);
    

    【讨论】:

      【解决方案2】:

      animal.findById(id).populate({path: 'species',populate: { path: "specialinfo" },})

      【讨论】:

        猜你喜欢
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多