Mongoose $push keeps adding two entries Mongoose $push keeps adding two entries mongoose mongoose

Mongoose $push keeps adding two entries


The problem is caused by your mixed used of promises (via async/await) and callbacks with the findOneAndUpdate call which ends up executing the command twice.

To fix the problem:

const updatedUser = await User.findOneAndUpdate(  { id: userID },  { $push: { addedItems: newProduct.id } },  { upsert: true, new: true });console.log(updatedUser);

Future readers note that the use of await isn't shown here in the question, but is in the MCVE.


I am facing similar issue. Just landed to this page. I find that previous answer is not very descriptive. So posting this:

export const updateUserHandler = async (req, res) => {    const request = req.body;     await  User.findOneAndUpdate(                  //<== remove await   { _id: request.id },  { $push: { addedItems: newProduct._id } },  { upsert: true, new: true },  (findErr, findRes) => {        if (findErr) {          res.status(500).send({            message: 'Failed: to update user',            IsSuccess: false,            result: findErr          });        } else {          res.status(200).send({            message: 'Success:  to update user',            IsSuccess: true,            result: findRes          });        }      });  }

Here there are two async calls one is the async and other is await. Because of this there are two entries in the document. Just remove await from await User.findOneAndUpdate. It will work perfectly.Thanks!!


When you await Query you are using the promise-like, specifically, .then() and .catch(() of Query. Passing a callback as well will result in the behavior you're describing.

If you await Query and .then() of Query simultaneously, would make the query execute twice

use:

await Model.findOneAndUpdate(query, doc, options)

OR

Model.findOneAndUpdate(query, doc, options, callback)