Home > OS >  How to use the findOne mongoDB query correctly?
How to use the findOne mongoDB query correctly?

Time:10-06

My goal is to get the one product object back depending on the product id i marked in green (out of the whole products array in my mongo DB)

enter image description here

My Backend entry looks as follows:

router.get("/:id", async (req, res)=> {
  const mid=req.params.id;
  console.log(mid)
  const products = await Product.findOne({ id: mid })
  console.log(products)
  if (products) {
    res.send(products);
  } else {
    res.status(404).send({message:"product not found"})
  } 
});

Connsole.log(mid) on line three works and it gives the right id back. However when i try to filter that one array depending on the value in line three i always get back the first object of my Database, which is the gopro camera, instead of the right object.

The Output looks as Follows:

632834528
{
  _id: '5f9849daf641a82b257d529b',
  id: 3484,
  agentId: 66343,
  title: 'GoPro Camera',
  slug: 'gopro',

What am i doing Wrong?

I tried const products = await Product.find({ id: mid }) as well, but it gives me the whole array back instead of just the one object.

CodePudding user response:

I think it's returning a Query. Try:

const products = await Product.findOne({ id: mid }).exec();

CodePudding user response:

This solution worked for me: I have to use the Expressasynchandler like this:

router.get("/:id",  expressAsyncHandler(async (req, res) => {
  const mid=req.params.id;
  console.log(mid)
  const products = await Product.findOne({ id: mid })
  console.log([products])
  if (products) {
    res.send([products]);
  } else {
    res.status(404).send({message:"product not found"})
  } 
}));
  • Related