When using the following method for upserting a document, twice, the createdAt
field gets recalculated, is there an option to avoid that?
model.findOneAndUpdate(
query,
doc,
{
upsert: true,
overwrite: true,
returnOriginal: false
}
);
Run example (query
== doc
):
model.findOneAndUpdate(
{ dataId: 'a', response: true },
{ dataId: 'a', response: true },
{
upsert: true,
overwrite: true,
returnOriginal: false
}
);
Then, running db.collection.find()
outputs:
{
_id: 601c46a1824900a958ae686b,
dataId: 'a',
response: true,
__v: 0,
updatedAt: 2021-02-04T19:10:25.417Z,
createdAt: 2021-02-04T19:10:25.417Z
}
When I try to update the document, with:
model.findOneAndUpdate(
{ dataId: 'a', response: true },
{ dataId: 'a', response: false },
{
upsert: true,
overwrite: true,
returnOriginal: false
}
);
Then, running db.collection.find()
again, 1 second later, outputs:
{
_id: 601c46a1824900a958ae686b,
dataId: 'a',
response: false,
__v: 0,
updatedAt: 2021-02-04T19:10:26.417Z,
createdAt: 2021-02-04T19:10:26.417Z
}
The createdAt
field gets regenerated (19:10:25
-> 19:10:26
).
question from:
https://stackoverflow.com/questions/66052493/mongoose-avoid-overwriting-createdat-on-findoneandupdate-overwrite