将$ currentDate的字段插入Meteor中的MongoDB集合

时间:2015-05-13 02:31:34

标签: javascript mongodb meteor mongodb-query

在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
  • 如果使用Moment.js esp,那么一个好处就是$ currentDate以ISO 8601格式输入。
  • 答案是从一开始就采取某种形式吗?如果是这样,这会产生意想不到的后果吗?

4 个答案:

答案 0 :(得分:23)

  

如果确实如此,那么拥有仅适用于更新的运算符的重点是什么?

$currentDateupdate operator,因此您无法将其与collection.insert方法一起使用。但是当upserttrue时,如果没有文档符合查询条件,它将创建新文档。 MongoDB运营商倾向于遵循Unix philosophy

  

做一件事并做得好

因此每个操作员只应执行一项任务。

  

为什么/何时$currentDate优于new Date

首先,我想提一下new Date是一个 JavaScript 日期实例。

当您想要将字段的值更新为当前日期时,可以使用

$currentDatenew 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)

在$ update构造中使用时,$ currentDate可用于插入字段中未存在的字段。

Mongodb 3.4的引用文档:     行为

If the field does not exist, $currentDate adds the field to a document.
相关问题