是否有任何方法来识别在mongoose/mongoDB中更新/中断

Is there any way to identify updated/upserted in mongoose/mongoDB?

本文关键字:mongoDB 更新 中断 mongoose 任何 方法 识别 是否      更新时间:2023-09-26

实际上我想知道是否有任何方法来识别更新的旧记录或添加的新记录使用findOneAndUpdate()与upsert: true选项在mongoose/mongoDB后?

我使用

// partial code 
var update = {$set:fieldsToSet};
    var options = {new: true, upsert:true};
    var created = yield User.findOneAndUpdate(fieldsQuery, update, options).exec();
// here I want to check updated old record or create new record

在模式中使用内置的timestamps选项,这样您就可以检查createAt字段。

var User = new Schema({
  ...,
  {
    timestamps: true,
});

这将自动添加createdAtupdatedAt字段到您的模式。


应用于你的代码

const callTime = new Date();
User.findOneAndUpdate(...)
 .then((ret) => {
    // It just get created
    if (ret.createAt.getTime() >= callTime.getTime()) {}
    // It get modified
 });