如何在猫鼬中填充许多模式

发布于 2025-02-09 10:09:07 字数 340 浏览 5 评论 0原文

请在这里给我解决方案 我打算编写一个共享搜索查询的通用函数,我使用mongodb + mongoose,

但是有一个我不知道如何动态使用pupulate()的问题。

例如:

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

我想填充许多其他模式,但仍然找不到将填充填充到此功能的方法(即:我可以在调用此功能时通过它传递的模式)? 谢谢你建议我 非常感谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城°AllureLove 2025-02-16 10:09:07

您可以在一个数组中收集所有填充命令,并在每个人查询中召集并使用。

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

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????
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文