Mongoose save method saves multiple times same document

Viewed 234

Hi I have one input field date selector on angular UI. I select the date from field and update the starting Date and till there it works correctly. but If I select the date again it duplicates the document instead of updating it.

working code:

router.post('/request/waiting/:startingDate', (req, res) => {
  const waiting = new WaitingRequest({
    startingDate: req.params.startingDate,
    requestID: req.body.requestID,
    contactInformation: req.body.contactInformation,
    orderInformation: req.body.orderInformation,
    requestInformation: req.body.requestInformation,
    installations: req.body.installations
  });
  waiting.save().then(result => {
    return res.status(201).json({
      message: 'Updated and Saved /waiting',
      result: result
    });
  });
});

what I have tried so far but it returns null:

router.post('/request/waiting/:startingDate', (req, res) => {
  WaitingRequest.findOneAndUpdate({
    requestID: req.body.requestID
  }, {
    startingDate: req.params.startingDate
  }).then(result => {
    console.log(result)
    if (result) {
      return res.status(201).json({
        message: 'Updated and saved',
        result: result
      });
    } else {
      return res.status(404).json({
        message: "404 Request Not Found"
      })
    }
  })
});
3 Answers

Use the UpdateOne() mongoose method to update your data,

router.post('/request/waiting/:startingDate', (req, res) => {
    let query = { requestID: req.body.requestID }
    let update = { $set: { startingDate: new Date(req.params.startingDate) } }
    WaitingRequest.updateOne(query, update,(error,result)=>{
        if(error) return res.status(404).json({ message: "404 Request Not Found" })
        return res.status(201).json({
            message: 'Updated and saved',
            result: result
        });
    })
});

You have to use the $set clause in the findOneAndUpdate

EDIT: Improving the code to use promise and sending a Date object as for starting date

Try this:

router.post('/request/waiting/:startingDate', (req, res) => {


WaitingRequest.findOneAndUpdate({
    requestID: req.body.requestID
  }, { $set: {
    startingDate: new Date(req.params.startingDate)
    }
  }).then(result => {
      return res.status(201).json({
        message: 'Updated and saved',
        result: result
      })
  }).catch(error => {
      res.send({ error })
   })
});

The reason for getting a 404 error is findOneAndUpdate was unable to find the required document based on requestID. The only missing piece to the puzzle is

new : bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)

router.post('/request/waiting/:startingDate', (req, res) => {

  WaitingRequest.findOneAndUpdate({
    requestID: req.body.requestID
    }, { $set: {
       startingDate: new Date(req.params.startingDate)
    }, {
       upsert:true, new: true,
    },
  }).then(result => {
       return res.status(201).json({
        message: 'Updated and saved',
        result: result
      })
  }).catch(error => {
       res.send({ error })
   })
});

Reference: mongoose docs

Hope this answers your question.

Related