猫鼬条件填充

问题描述 投票:0回答:1

我有这段代码,我想获取待处理的发票,我只想获取客户和金额字段。

const query = {status:"pending"};
const fields = "amount client";

const invoices = await Invoice.find(query,fields)
      .populate({model: 'User',path: 'currentResponsible'});
      .populate({model: 'User',path: 'responsible1'});
      .populate({model: 'User',path: 'responsible2'});
      .populate({model: 'Client', path: 'client'});

在这种情况下,mongoose 给了我待处理的发票,但用我不需要的信息填充字段“currentResponsible”、“responsible1”、“responsible2”,并且我没有在“fields”常量中请求这些信息。

我想要一个“条件填充”,如果我需要“字段”常量中的那个字段,它只会填充对象。

主要目标是创建一个模块化的 GET API 端点,允许我从前端发送“查询”和“字段”常量,以便仅从应用程序的不同部分获取我需要的信息。

我根据这个 other postdocumentation 尝试了以下方法,但是性能非常慢(检索和填充 1.300 个文档需要 1 分钟,这不是一个可行的解决方案。)

const query = {status:"pending"};
const fields = "amount client";

const invoices = await Invoice.find(query,fields)

const populatedInvoices = []
for (const invoice of invoices) {
  if(fields.includes("client")){
    await invoice.populate({model: 'Client', path: 'client'}).execPopulate();
  }
  if(fields.includes("currentResponsible")){
    await invoice.populate({model: 'User', path: 'currentResponsible'}).execPopulate();
  }
  if(fields.includes("responsible1")){
    await invoice.populate({model: 'User', path: 'responsible1'}).execPopulate();
  }
  if(fields.includes("responsible2")){
    await invoice.populate({model: 'User', path: 'responsible2'}).execPopulate();
  }
  populatedInvoices.push(invoice)
}

如果方法是“findOne()”(仅针对一个文档),则之前提到的帖子和文档中评论的解决方案有效,但就我而言,我希望它适用于“find()”(针对多个文档)

提前感谢您的帮助! :D

mongoose populate mongoose-populate
1个回答
0
投票

感谢 Chat GPT,我找到了解决方案 :D 由于并非发票模型的所有字段都需要填充,我创建了一个包含所有需要填充的字段的常量,这样如果我要求这些发票字段,我就会得到它们

const query = {status:"Pending",amount:{$gt:0}}
const fields = "client amount currentResponsible invoice status"
const INVOICE_FIELDS_TO_POPULATE = ['currentResponsible','responsible1', 'responsible2', 'client']
const invoices = await Invoice.find(query,fields).populate(fields.split(' ').filter(field=>INVOICE_FIELDS_TO_POPULATE.includes(field)).map((field) => ({ path: field })))

这样我就可以查询发票,只获取我需要的信息,并填写需要填充的字段。这种模式可以应用于 API 中的任何模型或资源。

© www.soinside.com 2019 - 2024. All rights reserved.