简体   繁体   中英

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

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))
  })

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",
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM