简体   繁体   English

如何在 Mongoose 中填充许多模式

[英]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请在这里给我解决方案我打算写一个通用函数来共享搜索查询,我使用MongoDB + Mongoose

But there is a problem that I don't know how to dynamically use populate().但是有个问题就是不知道怎么动态使用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 :您可以在一个数组中收集所有填充命令并调用 .populate 并使用 if 为每个人查询并在您的数组中添加推送新命令,并且所有这些命令都会在您的猫鼬查询中发送您的填充数组,例如:

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????
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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