我收到了一系列需要使用 Mongoose 搜索的產品,因此我使用 Find 傳遞每個產??品的 _id。但是當通過陣列并嘗試搜索時,我只收到第一個產品的資料,對于其他我總是收到未定義的資料。
這是我的代碼:
const calc = async (details) => {
let grandSubtotal = 0; }
console.log(details);
for (let i = 0; i < details.length; i ) {
let verifyProduct = await Product.find({ _id: details[i]._id});
console.log(verifyProduct[i].salePrice); //It only shows the first product, the others are undefined
.......
}
在我的 MongoDB 資料庫中,我始終使用 salePrice 保存所有產品,以這種方式:
{
"_id": "628fa841cde1d960c675ee24",
"barCode": "0000075053765",
"idProduct": "03",
"name": "MALBORO ARTESANAL 20",
"desc": "PAQUETE 20 CIGARROS",
"presentation": "PIECES",
"salePrice": 550,
"purchasePrice": 526,
"stock": 0,
"available": true,
"img": [],
"status": false
}
我如何獲得我收到的所有產品的 salePrice 資訊,因為現在我只收到第一個的資訊,其他的總是未定義的?
uj5u.com熱心網友回復:
這是因為,您正在使用.find({})
讓 verifyProduct = await Product.find({ _id: details[i]._id});
您正在使用 查詢.find({ _id: details[i]._id}),您將始終以 的形式獲得結果,[{..onevalue at 0..}]因為.find()回傳結果為[]
所以,當你第一次執行回圈時,你的i意志0,所以當你訪問它時,verifyProduct[0].salePrice它就會有價值。但是當你i變成時1,你仍然只會在位置verifyProduct有結果。0
使固定:
const calc = async (details) => {
let grandSubtotal = 0;
console.log(details);
for (let i = 0; i < details.length; i ) {
let verifyProduct = await Product.findById(details[i]._id);
// no array, so access it directly
console.log(verifyProduct.salePrice);
}
}
由于您是通過查詢_id,您可以使用.findById({})而不是.find()。
uj5u.com熱心網友回復:
for 回圈中的資料庫查詢效率極低。您應該使用$inMongoDB 運算子一次選擇多個檔案。
例子
const arrayOfIds = ["631318a217f73aa43a58855d", "63132ba7525da531e171c964"];
Product.find({ _id: { $in: arrayOfIds }});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/503957.html
標籤:javascript 节点.js 表示 猫鼬
