Meteor中的自动createdAt和updatedAt字段

在我的集合中,我想自动生成updatedAtupdatedAt字段,这些字段将包含最后一次插入/更新对象的date – 类似于Ruby on Rails中的情况。 目前我正在用类似这样的观察者来做这件事:

 MyCollection.find({}).observeChanges({ changed: function(id, changes) { MyCollection.update(id, ...); }, }); 

有更好/更有效/更直接的方法吗?

我喜欢https://github.com/matb33/meteor-collection-hooks

 collection.before.insert (userId, doc) -> doc.createdAt = new Date().valueOf #toISOString() 

我使用Collection2。 它支持autoValue中的autoValue ,一个计算字段强制值的函数。 由于这两个字段都用于所有集合,您可以将它们保存到一个variables中:

 @SchemaHelpers = createdAt: type: Date autoValue: -> if @isInsert return new Date if @isUpsert return $setOnInsert: new Date if @isUpdate @unset() return updatedAt: type: Date autoValue: -> return new Date 

然后在集合中:

 Schema = {} Posts = new Meteor.Collection("posts") Schema.Posts = new SimpleSchema createdAt: SchemaHelpers.createdAt updatedAt: SchemaHelpers.updatedAt title: type: String max: 30 body: type: String max: 3000 Posts.attachSchema(Schema.Posts) 

这个解决scheme使得updatedAt总是存在的,并且它的值将会非常接近updatedAt ,当它被插入时(不一定是相同的)。 如果您需要updatedAt插入时不要设置,您可以使用类似于Collection2自述文件中的示例:

 updatedAt: { type: Date, autoValue: function() { if (this.isUpdate) { return new Date(); } }, denyInsert: true, optional: true }, 

但是这不处理upserts 。 我不知道任何正确处理upserts的好方法,并在插入时将字段留空。