Hub*_* OG 2 javascript mongodb node.js meteor
在我的集合中,我想自动生成createdAt和updatedAt包含最后一次插入/更新对象的日期的字段 - 有点像Ruby on Rails中发生的那样.目前我正在与一个类似于此的观察者这样做:
MyCollection.find({}).observeChanges({
changed: function(id, changes) {
MyCollection.update(id, ...);
},
});
Run Code Online (Sandbox Code Playgroud)
有更好/更有效/更直接的方式吗?
我使用Collection2.它autoValue在模式中支持一个计算字段强制值的函数.由于这两个字段用于所有集合,您可以将它们保存到变量中:
@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
Run Code Online (Sandbox Code Playgroud)
然后在集合中:
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)
Run Code Online (Sandbox Code Playgroud)
该解决方案updatedAt始终存在,并且其值createdAt仅在插入时非常接近(不一定相同).如果updatedAt在插入时不需要设置,可以使用Collection2自述文件中的示例:
updatedAt: {
type: Date,
autoValue: function() {
if (this.isUpdate) {
return new Date();
}
},
denyInsert: true,
optional: true
},
Run Code Online (Sandbox Code Playgroud)
但这不会处理upserts.我不知道任何正确处理upserts的好解决方案,并且在插入时将字段留空.
| 归档时间: |
|
| 查看次数: |
3300 次 |
| 最近记录: |