![](/img/trans.png)
[英]Mongoose controller cant find a method from Repository
[英]Cant remap results from mongoose find operation
我有一條 API 路線,必須將所有發票退還給我,所以我有Invoice
model。 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);
}
};
和suppliersService.getAllSuppliers()
:
const getAllSuppliers = async () => {
try {
const suppliers = await Supplier.find().exec();
return suppliers;
} catch (err) {
return err;
}
};
find的結果是Model的數組,不是object的普通數組...
您可以轉換 find 的結果並使用它們:
注意:當你使用 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
當您可以使用populate()
方法時,當然不需要運行第二個查詢來獲取供應商數據,該方法允許您通過自動將文檔中的指定路徑替換為其他集合中的文檔來引用其他 collections 中的文檔)。
此外,鏈接lea lean()
方法以僅從查詢中返回普通對象,而不是像find()
方法這樣的 mongoose 文檔。 它還具有平均執行時間更短的好處,因為使用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.