How to populate multiple tables in mongodb to display in ejs?

Viewed 172

I have created three schemas. Here, animal schema references species schema, and species schema references specialinfo schema.

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:[]
});

I want to populate the animal schema such that I can access the special info data too.

This is my get request function for the index page.

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

I want to access the history and specialfeature field of the specialinfo schema from the index page. How can I do that? Thanks!

2 Answers

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

mongoose-autopopulate

you can use 'mongoose-autopopulate' and get automaticly populated data, and then you can populate species

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);
Related