简体   繁体   中英

How to populate to many schemas in Mongoose

Please give me the solution here I'm planning to write a common function to share for search queries, I use MongoDB + Mongoose

But there is a problem that I don't know how to dynamically use populate().

Ex:

const findData = async(model, populate, params) => {
   return await model
      .find(params)
      .populate() //issue????
};

I want to populate to many other Schemas but still can't find a way to pass populate to this function dynamically (ie: I can populate to the Schema it is passed in when calling this function)? Thank you for suggesting me Many thanks

you can collect all populate command in one array and called in .populate and use if for everyone query and add push new command in your array and all of them send your array of populate in your mongoose query like :

const findData = async(model, populate, params) => {

const popQuery = [];
if(req.query = "example1") {
popQuery.push({path:"user" , select: "name"})
}
if(req.query = "example2") { 
popQuery.push({path:"model2" , select: "name lastName age"})
}
if(req.query = "example3") {
popQuery.push({path:"model3" , select: "everything"})
}

   return await model
      .find(params)
      .populate(popQuery) //issue????
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM