在Meteor中将文档插入MongoDB集合时,不确定如何使用$currentDate。
这只能用于更新,而不是插入吗?看起来很奇怪,但我没有看到替代方案(而不是使用new Date
)。
示例
Stuff.insert({
owner: Meteor.userId(),
createdAt: ..., // how to create this field with $currentDate ?
theStuff: "Some of the good stuff"
})
备注/思考/ TL,DR
{}
。$currentDate
优于new Date
? 答案 0 :(得分:23)
如果确实如此,那么拥有仅适用于更新的运算符的重点是什么?
$currentDate
是update operator,因此您无法将其与collection.insert
方法一起使用。但是当upsert
为true
时,如果没有文档符合查询条件,它将创建新文档。 MongoDB运营商倾向于遵循Unix philosophy
做一件事并做得好
因此每个操作员只应执行一项任务。
为什么/何时
$currentDate
优于new Date
?
首先,我想提一下new Date
是一个 JavaScript 日期实例。
$currentDate
和new Date
,但使用new Date
时,您需要使用其他update operator工作。例如:
使用new Date
db.collection.update({ "name": "bar" }, { "$set": { "date": new Date() }})
使用$currentDate
db.collection.update({ "name": "bar"},
{ "$currentDate": { "date": { "$type": date }}}
)
与$currentDate
不同,new Date
可以与insert
方法一起使用,如果Date
调用多于on参数,则可以将值设置为特定值。
答案 1 :(得分:5)
您可以从插入操作中创建的自动生成的“_id”中检索时间戳。
http://api.mongodb.com/java/current/org/bson/types/ObjectId.html
只需使用方法:ObjectId.getTimestamp()。
时间戳粒度以秒为单位。
答案 2 :(得分:0)
如果在集合模型中使用autoValue,将变得更加简单
createdAt:
type: Date
autoValue: ->
if this.isInsert
return new Date
else if this.isUpsert
return $setOnInsert: new Date
else
this.unset()
在插入或更新数据时会自动设置日期
答案 3 :(得分:0)
Mongodb 3.4的引用文档: 行为
If the field does not exist, $currentDate adds the field to a document.