Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

node.js - Mongoose avoid overwriting createdAt on findOneAndUpdate overwrite

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...