Multiple populates - mongoosejs

后端 未结 8 1722
傲寒
傲寒 2020-12-04 17:33

Just a simple query, for example with a double ref in the model.

Schema / Model

var OrderSchema = new Schema({

    user: {
                 


        
相关标签:
8条回答
  • 2020-12-04 17:59

    Latest mongoose v5.9.15 has ability to take array of populate fields so you can do,

    .populate([ 'field1', 'field2' ])
    
    0 讨论(0)
  • 2020-12-04 18:03

    You can try:

    OrderModel.find()
        .populate('user')
        .populate('meal')
        .exec(function (err, results) {
             // callback
        });
    

    or with array options

    OrderModel.find()
        .populate([
          {
            path: "path1",
            select: "field",
            model: Model1
          },
          {
            path: "path2",
            select: "field2",
            model: Model2
          }
        ])
        .exec(function (err, results) {
             // callback
        });
    
    0 讨论(0)
  • 2020-12-04 18:06

    You're already using the correct syntax of:

    OrderModel.find()
        .populate('user')
        .populate('meal')
        .exec(function (err, results) {
             // callback
        });
    

    Perhaps the meal ObjectId from the order isn't in the Meals collection?

    0 讨论(0)
  • 2020-12-04 18:07

    i have same problem , but my mistake not in populate , i have an error in Model

    if you do this

    uncorrected

    user: {
     type: [Schema.Types.ObjectId],
     ref: 'User'
    } 
    

    correct

    user: [{
     type: Schema.Types.ObjectId,
     ref: 'User'
    }]
    

    you must put array around of object like this

    0 讨论(0)
  • 2020-12-04 18:08

    UPDATE:
    This solution remains for the version 3.x of Mongoose
    http://mongoosejs.com/docs/3.8.x/docs/populate.html
    but is no longer documented for >= 4.x versions of Mongoose and so the answer from @JohnnyHK is the only valid one for now on.

    ORIGINAL POST
    If you're using Mongoose >= 3.6, you can pass a space delimited string of the path names to populate:

    OrderModel.find()
        .populate('user meal')
        .exec(function (err, results) {
             // callback
        });
    

    http://mongoosejs.com/docs/populate.html

    0 讨论(0)
  • 2020-12-04 18:09

    To populate multiple fields with array of objects in controller/action function, model of both is already referred in schema of post

    post.find({}).populate('user').populate('comments').exec(function (err,posts)
        {
        
        if(err)
        {
            console.log("error in post");
        }
        
            return  res.render('home',{
                h1:"home Page",
                posts:posts,
                
                });      
            });
    
    0 讨论(0)
提交回复
热议问题