在Mongoose中存储用户提供的日期

时间:2014-12-08 02:48:35

标签: node.js mongodb mongoose

所以,我已经有了这个架构:

var imageSchema = new Schema( {
  caption: {type: String, required: true},
  url: {type: String, required: true}
});


var EventSchema = new Schema({

  name: {type: String, required: true},
  date: {type: Date, required: true},
  time: {type: String, required: true},
  location: {type: String, required: true},
  description: { type: String, required: false },
  image: {type: String, required: false},
  images: [imageSchema]


});

请求通过locomotive.js处理,用于创建新记录的控制器操作如下所示:

EventController.create = function() {
  if(preScreen.screen.bind(this)("event", "create")) {
    this.elements = modelHelper.loadValues.bind(this)();

    this.saveMessage = "Save";
    this.strings = strings;

    if(this.req.method && this.req.method == "POST") 
    { 
        this._createEvent();
    } else {
        this.render();
    }
  } else {
    this.redirect(this.urlFor({controller: "dashboard", action: "error"}));
  }
};

这是一个相当标准的动作控制器;主要是在使用POST标头收到时调用输入视图或处理_create。

_createEvent函数如下所示:

EventController._createEvent = function() {
  if(!(this.elements)) this.elements = require('../templates/Event/elements')();
  if(!(this.event)) this.event = new Event(); 

  modelHelper.populate.bind(this)(this.elements, "event",  function() {
    modelHelper.save.bind(this)("event", this._confirm.bind(this), "create");
  }.bind(this));
};

对于我的模型,我将所有输入封装在模板模式中。而不是花费大量时间在这个框架周围(我正在努力发布开源,一旦我完成了小的调整)我会说有效的模板包含一个元素为模式中的每个路径,并提供一些客户端 - 详细信息(错误消息,标签等)这些模板对象由modelHelper对象使用,该对象是相当不可知的。有效地,modelHelper.populate所做的是检查"类型"元素中每个对象的属性,并调用适当输入类型的处理程序。

日期类型的处理程序是:

    case "date" :
    this[record][field.name] = strings.exists(this.param(field)) ?
            strings.trim(this.param(field.name)) : null;

    break;

虽然我也尝试过strings.trim(Date.parse(this.param(field.name))来从用户字符串中获取UTC时间戳。

我已经能够通过在日期解析器中使用console.log验证用户输入的日期字符串是否返回了有效的UTC标记。

当调用modelHelper.save()时,它会遍历这些模板对象,使用从解析器中拾取的值创建一个关联数组,并将其传递给Record.save()。

大部分已经过全面测试并且正在生产中使用,但这是我第一个使用date.now()以外的日期作为默认值的情况。

为了让mongodb / mongoose驱动程序将日期推送到Date类型,日期解析器的正确主体是什么?

1 个答案:

答案 0 :(得分:3)

JavaScript的Date.parse方法可以解析的任何字符串都可以使用Mongoose使用调用Date {this function强制转换为Date的字符串。 {3}}使用Date.parse来解析字符串。