Skip to content
Advertisement

Undefined when searching with Find Mongoose Express

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 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:

JavaScript

In my MongoDB database I have the products all saved with salePrice always, in this way:

JavaScript

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?

Advertisement

Answer

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:

JavaScript

since you are querying by _id, you can use .findById({}) instead of .find().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement