【问题标题】:Mongoose.js ignoring default value in subdoc SchemaMongoose.js 忽略 subdoc Schema 中的默认值
【发布时间】:2015-04-28 18:53:15
【问题描述】:

我目前正在使用 mongodb 和 mongoose 编写一个 Web 应用程序。我定义了一个文档模式,它有一个子文档数组。我在不同的架构中定义了子文档。子文档的字段具有默认值,例如:end: {type: Date, default: Date.now}。不幸的是,在创建带有一些子文档的父文档时,只设置了我明确设置的子文档的字段。 mongoose 似乎忽略了default 选项。

你们知道我做错了什么吗?

编辑:

employment.model.js

var Shift = require('./shift.model.js').ShiftSchema;

var EmploymentSchema = new Schema({
    title: {type: String, required: true},
    ....
    shifts: [Shift]
});

shift.model.js

var ShiftSchema = new Schema({
   title: {type: String},
   ....
   info: {type:String, default: 'Hallo'},
   start: {type: Date, default: Date.now, index: true},
   end: {type: Date, default: Date.now}
});
module.exports.ShiftSchema = ShiftSchema;
module.exports = mongoose.model('Shift', ShiftSchema);

以上default 值均未设置。 我的 mongoose.js 版本是:~3.8.8

样本班次创建

Employment.create({
    title: 'PopulateDB Employ',
    start: new Date(),
    customer: result.customer,
    shifts: [{
      title: 'Shift 1',
      start: new Date()
    },{
      title: 'Shift 2',
      start: new Date()
    }]
  },cb)

【问题讨论】:

  • 另外我的子文档没有 id 字段....我现在很无助 ;-)

标签: node.js mongodb mongoose


【解决方案1】:

您正在使用下一条语句覆盖您的ShiftSchema 导出,该语句将模型指定为模块的唯一导出。结果是Shiftemployment.model.js 中以undefined 结尾。

将该文件的第一行更改为以下内容以从导出的模型访问架构:

var Shift = require('./shift.model.js').schema;

只需删除 shift.model.js 中的 module.exports.ShiftSchema = ShiftSchema; 行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2015-11-26
    相关资源
    最近更新 更多