Undefined when searching with Find Mongoose Express

Issue

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:

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?

Solution

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().

Answered By – Sridhar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published