Mongoose: multiple query populate in a single call

后端 未结 4 463
盖世英雄少女心
盖世英雄少女心 2020-12-01 03:08

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as

Person.find({})
 .populate(\         


        
相关标签:
4条回答
  • 2020-12-01 03:53

    you can also do something like below:

    {path:'user',select:['key1','key2']}
    
    0 讨论(0)
  • 2020-12-01 03:55

    This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html

    Let's say you have a BookCollection schema which contains users and books In order to perform a query and get all the BookCollections with its related users and books you would do this

    models.BookCollection
        .find({})
        .populate('user')
        .populate('books')
        .lean()
        .exec(function (err, bookcollection) {
        if (err) return console.error(err);
        try {
            mongoose.connection.close();
            res.render('viewbookcollection', { content: bookcollection});
    
        } catch (e) {
            console.log("errror getting bookcollection"+e);
        }
    
    0 讨论(0)
  • 2020-12-01 04:03

    You achieve that by simply passing object or array of objects to populate() method.

    const query = [
        {
            path:'books', 
            select:'title pages'
        }, 
        {
            path:'movie', 
            select:'director'
        }
    ];
    const result = await Person.find().populate(query).lean();
    

    Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!

    0 讨论(0)
  • 2020-12-01 04:10

    After looking into the sourcecode of mongoose, I solved this with:

    var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
    
    Person.find({})
     .populate(populateQuery)
     .execPopulate()
    
    0 讨论(0)
提交回复
热议问题