如何在Mongoose的upsert操作中设置更新时间戳?

我想设置更新时间戳只用于在upsert操作中更新logging(并插入新logging的时间戳)。

self.model.update({Id: obj.Id}, obj, {upsert: true}, function(err){ if (err) { return; } //... }); 

有没有办法处理这个?

有一个pre.save中间件我可以使用也许,但有什么办法告诉当前的操作是插入还是更新?

提前致谢!

你不能自动执行。 你可以在upsert上使用$set: { timestamp: Date.now() }来完成。

在讨论此问题的mongoosebugtracker中存在一个封闭的问题,在这里: 默认值在upsert上被忽略

有点晚了,但希望能帮到别人!

你可以使用预存储钩子,有一些像.isNew或.isModified的标志可以使用。

 self.schema.pre('save', function (next) { if (this.isNew) { this.updated = Date.now(); } return next(); } 

对于创builddate,可以从ObjectId中提取时间戳

为插入

 db.test.insert({ts:new Date()}) 

为upsert

 db.test.update({"_id" : ObjectId("540815fa802a63ddca867bc0")},{$set:{ts:new Date()}},{upsert:1}) 

这里有一个mongoose插件(Mongoose Timestamps Plugin)

这是CoffeeScript的实现 – 使用js2coffe.com转换为js,如果你需要的话。

你可以在你所有的模型中使用它。

创build一个函数如下

 # * Mongoose Timestamps Plugin # * Copyright(c) 2012 Nicholas Penree <nick@penree.com> # * Original work Copyright(c) 2012 Brian Noguchi # * Modified from Fino 2014 # * MIT Licensed # timestamps = (schema, options) -> updated_at = "updated_at" created_at = "created_at" updatedAtType = Date createdAtType = Date if typeof options is "object" if typeof options.updated_at is "string" updated_at = options.updated_at else if typeof options.updated_at is "object" updated_at = options.updated_at.name or updated_at updatedAtType = options.updated_at.type or updatedAtType if typeof options.created_at is "string" created_at = options.created_at else if typeof options.created_at is "object" created_at = options.created_at.name or created_at createdAtType = options.created_at.type or createdAtType dataObj = {} dataObj[updated_at] = updatedAtType if schema.path("created_at") schema.add dataObj schema.virtual(created_at).get -> this["_" + created_at] if this["_" + created_at] return this["_" + created_at] = @_id.getTimestamp() schema.pre "save", (next) -> if @isNew this[updated_at] = this[created_at] else this[updated_at] = new Date next() return else dataObj[created_at] = createdAtType schema.add dataObj schema.pre "save", (next) -> unless this[created_at] this[created_at] = this[updated_at] = new Date else this[updated_at] = new Date next() return return 

然后在你的mongoose模型中做下面的事情

userSchema.plugin时间戳

而已!

这将添加created_at并保持update_at更新,因为您继续使用“model.save()”