[英]Cant remap results from mongoose find operation
I have an API route that must give me back all the invoices and so I have Invoice
model.我有一条 API 路线,必须将所有发票退还给我,所以我有
Invoice
model。 There is a supplierId
field in that model, that saves the _id
of the respective supplier of the invoice, which means that whenever I want to pull the invoices, I must also pull the respective suppliers and incldue them in the response, and that is my issue, for some reason, I can't work on the results as I do on normal arrays: model中有一个
supplierId
字段,它保存了发票各自供应商的_id
,这意味着每当我要拉发票时,我还必须拉相应的供应商并将它们包含在响应中,这就是我的问题,由于某种原因,我无法像在正常 arrays 上那样处理结果:
const getAllInvoices = async (req, res) => {
try {
const invoices = await Invoice.find().exec();
const suppliers = await suppliersService.getAllSuppliers();
const invoicesWithSuppliers = invoices.map((invoice) => {
return {
number: invoice.number,
supplierName: suppliers.find((supplier) => supplier._id === invoice.supplierId).name,
};
});
console.log(invoicesWithSuppliers); // outputs nothing
res.json(invoices); // and this now for some reason also stops working and returns {}
} catch (err) {
res.json(err);
}
};
And suppliersService.getAllSuppliers()
:和
suppliersService.getAllSuppliers()
:
const getAllSuppliers = async () => {
try {
const suppliers = await Supplier.find().exec();
return suppliers;
} catch (err) {
return err;
}
};
the result of find is array of Model, not a common array of object... find的结果是Model的数组,不是object的普通数组...
you can convert the result of find and working with them:您可以转换 find 的结果并使用它们:
note : when you use awai, no need to exec()
注意:当你使用 awai 时,不需要
exec()
let invoices = await Invoice.find();
invoices = invoices.map((inv) => inv.toObject({ getters: true }));
let suppliers = await suppliersService.getAllSuppliers();
suppliers = suppliers.map((sup) => sup.toObject({ getters: true }));
//do somthing
There's certainly no need to run a second query to get the suppliers data when you can just use populate()
method which lets you reference documents in other collections by automatically replacing the specified paths in the document with document(s) from other collection(s).当您可以使用
populate()
方法时,当然不需要运行第二个查询来获取供应商数据,该方法允许您通过自动将文档中的指定路径替换为其他集合中的文档来引用其他 collections 中的文档)。
Also, chain the lean()
method to return only plain objects from the query, not mongoose documents like the find()
method.此外,链接lea
lean()
方法以仅从查询中返回普通对象,而不是像find()
方法这样的 mongoose 文档。 It also has the benefit of less average execution time simply because the documents returned with the lean()
method are plain javascript:它还具有平均执行时间更短的好处,因为使用
lean()
方法返回的文档是普通的 javascript:
const getAllInvoices = async (req, res) => {
try {
const invoices = await Invoice.find()
.populate('supplierId', 'name')
.lean();
res.json(invoices);
} catch (err) {
res.json(err);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.