Home > Enterprise >  Fetching data from mongo db collection failing to found data
Fetching data from mongo db collection failing to found data

Time:10-14

I'm using mongo db and angular for an eCommerce application.

Requirement is to get items under each user in cart.

Here while fetching I'm using the objectId as the reference to find the data, Its not finding out any data from the DB.

exports.findAllCartItems = (req, res) => {
  const id = req.params.id;
   insertTocartItem.find(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Cart Is empty" });
      else res.send([data]);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error while showing Cart" });
    }); 
};

Data In collection:

  "_id": "$oid": "6347caf515a675847127b020"
  "parentcategoryId": 1000,
  "brandName": "Nothing",
  "modelName": "1",
  "Price": "30000",
  "itemsImage": "http://localhost:8080/public/1664539223328--Nothing_phon.jpg",
  "itemsubCatId": "7000",
  "itemId": "7000MB1",
  ***"userInfoId": "634677b7ce60d9d8cd591940",***
  "__v": 0

I'm passing userInfoId": "634677b7ce60d9d8cd591940 from frontend, I'm able to see the ID in req.params.id but unable to find the matching data.

If changed insertTocartItem.find(id) to insertTocartItem.find({id}) it is fetching entire data in the cart irrespective of userInfoId.

Kindly help with any method to find the data based on userInfoId.

CodePudding user response:

You need to instruct in the query which field you want to search.

exports.findAllCartItems = (req, res) => {
  const id = req.params.id;
   insertTocartItem.find({userInfoId: id})
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Cart Is empty" });
      else res.send([data]);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error while showing Cart" });
    }); 
};

CodePudding user response:

See you have to pass id in _id property to find the data like this,

insertTocartItem.find({_id: id}) // Here, replace '_id' with which field you want to search for, for ex: {userInfoId: id}

The thing is mongoose schema is an object based right so infind() method you have to pass schema property key that is _id and value that is req.params.id.

Or If you dont want to pass an object then you can use findById() method like this,

insertTocartItem.findById(id)

CodePudding user response:

insertTocartItem.find({_id: id})

You should indicate which field you wanna apply the request to...

  • Related