【问题标题】:Is there any way to identify updated/upserted in mongoose/mongoDB?有什么方法可以识别 mongoose/mongoDB 中的更新/更新?
【发布时间】:2016-11-10 21:33:57
【问题描述】:

其实我想知道在mongoose/mongoDB中使用 findOneAndUpdate() 和 upsert: true 选项后有什么方法可以识别更新的旧记录或添加的新记录?

我正在使用

// 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

【问题讨论】:

  • 您不能同时使用选项{new: true, upsert: true},因为原子更新仅返回使用该操作修改的文档;您可能需要单独查询以返回未修改的文档,即var original = yield User.findOne(fieldsQuery).exec();
  • @chridam 我同时使用并工作,但是我的问题是有什么方法可以识别更新的记录或创建新的记录。感谢您的重播

标签: javascript node.js mongodb mongoose


【解决方案1】:

在您的架构中使用内置的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
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2016-12-09
    相关资源
    最近更新 更多