MongoDB / Mongoose时间戳没有更新

时间:2016-09-14 16:40:43

标签: node.js mongodb mongoose-schema

架构:

var schema = new Schema({...}, {
    timestamps: true,
    id: false,
    toJSON: {
        virtuals: true,
    },
    toObject: {
        virtual: true,
    }
});
schema.virtual('updated').get(function () {
    if(typeof this.updatedAt === "undefined" && typeof this.createdAt === "undefined") return "";
    var updated = (typeof this.updatedAt === "undefined") ? this.createdAt : this.updatedAt;
    return "Updated "+moment(updated).fromNow();
});

此代码 最近正在运行 - 针对特定实例的updatedAt将于8月24日发布,但对文档的任何新修改都不会更新时间戳。

感觉我在这里错过了一些非常愚蠢的东西。

4 个答案:

答案 0 :(得分:3)

可以尝试修改您的架构,如:

var schema =new Schema({..}, 
           { timestamps: { createdAt: 'createdDate',updatedAt: 'updatedDate' } 
});
此模式时间戳的

将在save()update()findOneAndUpdate()上更新。所以不需要schema.virtual('updated')...

<强>过程-2

在您的架构中添加了createdDateupdatedDate Date类型,并使用架构插件更新这些日期字段。

像:

var mongoose = require('mongoose'),
    Schema   = mongoose.Schema,
    SchemaPlugin = require('../helpers/schemaPlugin');
  var schema =new Schema({..},
    createdDate: {
      type: Date,
      default: Date.now
    },
    updatedDate: {
      type: Date,
      default: Date.now
    }
  });

  schema.plugin(SchemaPlugin);
<{1>}文件中的

schemaPlugin.js

答案 1 :(得分:1)

updatedAt和createdAt都是在使用mongoose将新文档输入数据库的同时创建的,因此检查updatedAt是否未定义是不合逻辑的,因为在创建新文档时两者都具有相同的值。

每当您使用mongoose更新函数或findByIdAndUpdate或findOneAndUpdate时,updatedAt的值将自动更新。使用Mongongb客户端(如mongochef或robomongo)直接检查updatedAt的值。

答案 2 :(得分:1)

偶然发现同一件事,发现如果用updatedAt(或findOneAndUpdate())更新对象时,如果在我的对象上设置了属性update(),它将不会更新它。

对于我来说,请确保在更新前未设置updatedAt来解决此问题:

delete thing.updatedAt;

Thing.findOneAndUpdate(
  { _id : thing._id },
  thing,
  function (err, result) {
   …

Credit to Valeri Karpov for his answer on Github.

答案 3 :(得分:0)

您正在将objectString进行比较,这就是为什么条件始终为false

schema.virtual('updated').get(function () {
    if(typeof this.updatedAt === undefined && typeof this.createdAt === undefined) return "";
    var updated = (typeof this.updatedAt === undefined) ? this.createdAt : this.updatedAt;
    return "Updated "+moment(updated).fromNow();
});

试试这个,它应该可行

相关问题