Mongodb 插入空日期

kar*_*mac 4 mongoose mongodb node.js

邮件架构:

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}
        }
    ]
});
Run Code Online (Sandbox Code Playgroud)

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

Mail validation failed: endDate: Cast to Date failed for value "null"
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 6

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

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

const newMail = mail.create({
    globalId: "1234",
    from: "Jack",
    beginDate: new Date(),
    subject: "Random subject",
});
Run Code Online (Sandbox Code Playgroud)

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

endDate: null

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