2016-09-14 49 views
7

模式:的MongoDB /猫鼬时间戳更新不及时

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日,但任何新的编辑文档更新时间戳。

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

+0

你能检查type.of this.updatedAt吗? – abdulbarik

+0

@abdulbarik typeof league.updatedAt => object –

+0

我复制粘贴你的代码并运行在我的服务器上,它与猫鼬4.6.1一起工作得很好,所以你可能错过了别的地方。 请提及您正在使用的猫鼬版本,或任何猫鼬插件。 –

回答

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(); 
}); 

试试这个,它应该工作

+0

感谢您的回答,但似乎问题并没有成为的那部分 - 问题与updatedAt时间戳不更新的编辑。 –

+0

是否意味着您的状况良好? – abdulbarik

+0

你卡在哪个地方? – abdulbarik

2

可以尝试通过修改您的模式,如:

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); 

schemaPlugin.js文件:

module.exports = function(schema) { 

    var updateTimestemps = function(next){ 
    var self = this; 


    if(!self.createdAt) { 
     self.createdDate = new Date(); 
     //or self.update({},{ $set: { createdDate : new Date(), updatedDate: new Date() } }); 
    } else { 
     self.updatedDate= new Date(); 
     //or self.update({},{ $set: {updatedDate: new Date() } }); 
    } 
    next(); 
    }; 

    schema. 
    pre('save', updateTimestemps). 
    pre('update', updateTimestemps). 
    pre('findOneAndUpdate', updateTimestemps); 
}; 
1

updatedAt和createdAt都在同一时间创建时使用猫鼬被输入到数据库中的一个新的文档,你的检查是否updatedAt是未定义或不是不合逻辑的,因为在创建新文档时两者都具有相同的值。

无论您何时使用猫鼬更新函数或findByIdAndUpdate或findOneAndUpdate,updatedAt的值都会自动更新。使用Mongodb客户端(如mongochef或robomongo)直接检查updatedAt的值。