Meteor new Date() 对 mongodb 3.0.1 和 autoform/simple 模式无效

Meteor new Date() invalid with mongodb 3.0.1 and autoform/simple schema

我无法将 type: Date 处理成具有默认值的 SimpleSchema。 在 mongodb (3.0.1) 中,日期条目包含 meteor 线程启动的时间。预期的行为是 "date" 服务器上对象的插入日期。

lib/schema.js

Schema.DateCol = new SimpleSchema({
  date: {
    type: Date,
    defaultValue: new Date()
  },
  dateModified: {
    type: Date,
    autoValue: function () { return new Date(); }
  }
});

client/home.html

    {{> quickForm id="test" schema="Schema.DateCol" collection="DateCol" type="insert" }}

进入mongo后,插入两个对象:

对象 1

{
  "_id": "PuME9jWwJJiw9diSC",
  "date": new Date(1432117722634),
  "dateModified": new Date(1432117850366)
}

对象 2:

{
  "_id": "qqHqkN4YapWDsFhxx",
  "date": new Date(1432117722634),
  "dateModified": new Date(1432117890380)
}

您最终会使用 MongoDB 3.0.1 将错误包含在存储库 Github 中(我在 MongoDB 2.4 上没有此错误): https://github.com/JVercout/meteor-defaultValue-date-errored

有什么想法吗?

问题是当创建模式的代码是 运行 时,new Date() 表达式被计算一次。然后将该值用作 defaultValue。两者没有区别:

var x = new SimpleSchema({
  date: {defaultValue: new Date(), ...}
});

var defaultDate = new Date();
var x = new SimpleSchema({
  date: {defaultValue: defaultDate, ...}
});

您似乎需要 autoValue,因为您似乎无法使用 defaultValue 的函数。 Collection2 documentation 实际上有一个使用 autoValue 作为“创建于”字段的示例。这取决于 Collection2 添加的字段,但我在您的 git 存储库中看到您正在使用它。

// Force value to be current date (on server) upon insert
// and prevent updates thereafter.
createdAt: {
  type: Date,
  autoValue: function() {
    if (this.isInsert) {
      return new Date();
    } else if (this.isUpsert) {
      return {$setOnInsert: new Date()};
    } else {
      this.unset();
    }
  }
}