Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongodb插入空日期_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js Mongodb插入空日期

Node.js Mongodb插入空日期,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,邮件架构: 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:

邮件架构:

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"

看起来您试图用无效的结束日期保存架构

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

const newMail = mail.create({
    globalId: "1234",
    from: "Jack",
    beginDate: new Date(),
    subject: "Random subject",
});
如果你想做这样的事情

endDate:null


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

正如您所提到的,您将
endDate
存储为
null
字符串。这肯定会失败,因为您的模式需要一个日期,而您正在存储字符串

您可以采用多种方法:

  • 避免来自JSON对象的
    endDate
    。(MongoDB中没有endDate密钥)
  • 设置将自动忽略的
    endDate:undefined
    。(MongoDB中没有endDate密钥)
  • 设置
    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

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

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

    将endDate为
    未定义的新邮件保存为
    保存新数据时不传递结束日期