MongoDB插入空日期

时间:2018-10-22 06:42:52

标签: node.js mongodb mongoose

邮件Shcema:

var mail = new mongoose.Schema({
    globalId: {type: String, index: true, unique: true},
    from: {type: String, required: true},
    beginDate: {type: Date, required: true},
    endDate: {type: Date},
    source: {type: String},
    address: {type: String},
    subject: {type: String, required: true},
    text: {type: String},
    note: {type: String},
    files: [
        {
            fileName: {type: String},
            fileSize: {type: Number},
            fileType: {type: String}
        }
    ]
});

当我尝试使用endDate保存新邮件为空时,出现以下错误

Mail validation failed: endDate: Cast to Date failed for value "null"

3 个答案:

答案 0 :(得分:2)

您似乎正在尝试使用无效的endDate保存架构。

如果您不想保存日期,只需将其从对象中删除即可。例如,您所需提供的架构至少为:

const newMail = mail.create({
    globalId: "1234",
    from: "Jack",
    begineDate: new Date(),
    subject: "Random subject",
});

如果您尝试做类似的事情,

endDate: null

这将失败,因为它期望一个Date()对象或什么都没有。

答案 1 :(得分:0)

正如您提到的,您将endDate作为null存储为String。这肯定会失败,因为您的架构需要一个日期并且您正在存储String。

多种处理方式:

  1. 避免使用JSON对象中的endDate(您在MongoDB中将没有endDate密钥)
  2. 设置endDate: undefined,它将自动被忽略。 (您在MongoDB中将没有endDate密钥)
  3. 设置endDate: null 不在字符串中 (您将endDate键作为null值)

以下一项将无效:

var testObj = {
    ct: "null", // null as String value
    name: "Foo"
}

但是这个绝对可以工作:

var testObj = {
    ct: null, // null as value
    name: "Foo"
}

在以下版本上进行了测试:

MongoDB v3.2.18
猫鼬 v4.10.8

我想在这里添加的另一点是存储key: null将消耗资源。如果您的要求不依赖于null值,我想使用不将密钥存储在数据库中而不是存储为null

答案 2 :(得分:0)

我已通过将默认日期设置为undefined解决了这一问题。创建对象时不会显示。很好,因为它现在是前端问题。如果不存在密钥,则前端将默认为undefined。如果未定义,它将不会保存在数据库中。避免使用默认的null我也犯了这个错误!

mail = {
  endDate: {
   type: Date,
   default: undefined
  }
}