首页 文章

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

提问于
浏览
0

所以,我有这个架构:

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所做的是检查元素中每个对象的“type”属性,并调用适当输入类型的处理程序 .

日期类型的处理程序是:

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 回答

  • 3

    JavaScript的Date.parse方法可以解析的任何字符串都将起作用,因为使用this function将字符串强制转换为 Date ,调用 Date constructor,它使用 Date.parse 来解析字符串 .

相关问题