I receive an array of products that I need to search for with Mongoose so I use Find passing the _id of each product. But it happens that when going through the array and trying to search, I only receive the data of the first product, for the others I always receive undefined.
This is my code:
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
.......
}
In my MongoDB database I have the products all saved with salePrice always, in this way:
{
"_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
}
How can I obtain the salePrice information of all the products that I receive since for now I only receive information on the first one and the others are always undefined
CodePudding user response:
your .find()
returns an array of just 1 object everytime and since after 0
in the for loop i
wouldn't equal 0 (like 1 2 3 etc) the verifyProduct[i]
would be undefined like verifyProduct[2]
doesn't exist since verifyProduct
is just an array with a single element
Try
const calc = async (details) => {
let grandSubtotal = 0; }
console.log(details);
for (let i = 0; i < details.length; i ) {
let verifyProduct = await Product.findOne({ _id: details[i]._id});
console.log(verifyProduct.salePrice); //It only shows the first product, the others are undefined
.......
}
CodePudding user response:
this because, you are using .find({})
let verifyProduct = await Product.find({ _id: details[i]._id});
You're querying using .find({ _id: details[i]._id})
, you will always have result in the form of [{..onevalue at 0..}]
because .find()
returns result in an []
so, when you execute the loop for the first time, your i
will be 0
and so when you access the verifyProduct[0].salePrice
it will have value. But when your i
become 1
, your verifyProduct
will still have result at 0
position only.
Fix:
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);
}
}
since you are querying by _id
, you can use .findById({})
instead of .find()
.