Mongoose update $setOnInsert changes updatedAt timestamp even when no update occurs

Viewed 1053

I have a schema with timestamps: true paramter. I want to insert documents but only if they do not already exist. If they do exists, no operation should occur (noop).

so I use $setOnInsert paramter as following

return Order.findByIdAndUpdate(
        order._id,
        {
          $setOnInsert: order
        },
        {
          upsert: true,
          new: true
        });

If I understood correctly this should only insert the doc if it does not already exists and otherwise perform no update.

But what happens is that the updatedAt timestamp gets updated whenever I run this operation.

How can I prevent this? Is this intended behaviour or have I chosen the wrong approach to "insert only if not exists"?

2 Answers

findOneAndUpdate accepts a timestamps option which (when set to false) allows you to skip updating timestamps.

For example:

return Order.findByIdAndUpdate(
  order._id,
  {
    $setOnInsert: order
  },
  {
    timestamps: false,
    upsert: true,
    new: true
  }
);

You can see the relevant documentation here.

Add createdAt: new Date() and updatedAt: new Date() in $setOnInsert block, and add timestamps: false in options block.

It means: If the data is not found, create the data and add a timestamp, if the data is found, do nothing (including not updating the time stamp).

For example:

return Order.findByIdAndUpdate(
  order._id,
  {
    $setOnInsert: {
      ...order,
      createdAt: new Date(),
      updatedAt: new Date()
    }
  },
  {
    timestamps: false,
    upsert: true,
    new: true
  }
);
Related