How to check if there are no more documents to update using findOneAndUpdate Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to check if there are no more documents to update using findOneAndUpdate without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I am learning CRUD for a school project and I followed a tutorial that was really useful. However, when I completed it I noticed that when there are no more quotes to update, it still updates quotes. How can I change this so that it will stop updating quotes that arent even there?

  app.put('/quotes', (req, res) => {
    quoteCollection.findOneAndUpdate(
      { name: 'Yoda' },
      {
        $set: {
          name: req.body.name,
          quote: req.body.quote
        }
      },
      {upsert: true}
    )
    .then(result => {
      //The if block that i am trying
      if (result.deletedCount === 0) {
        return res.json('No quote to delete')
      }
    })
    .catch(error => console.error(error))
  })

Answer

Why are you passing {name: "Yoda}? This route is supposed to only update the quote with “Yoda” as its name? If not, then you need to grab from the request object the quote that should be updated.

I tried to create a different version, based on the assumption that the quote that should be updated will come from the req.body:

app.put("/quotes", async (req, res) => {
  //Grab the name/id/identifier for the quote you want to update from the body
  const query = req.body.name;

  // Try to update the document on the database
  try {
    const result = await quoteCollection.findOneAndUpdate(
      query,
      {
        name: req.body.name,
        quote: req.body.quote,
      },
      {
        upsert: true,
        new: true,
      }
    );

    // If it worked, it will return the updated quote
    res.status(200).json({
      status: 200,
      data: {
        result,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: 400,
      message: "Something went wrong",
    });
  }
});
We are here to answer your question about How to check if there are no more documents to update using findOneAndUpdate - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji