'Mongodb insert null date

Mail Schema:

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}
        }
    ]
});

When I try to save new mail with endDate is null I have the following error

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


Solution 1:[1]

It looks like you are trying to save the schema with an invalid endDate.

If you do not want to save a date simply leave it out from the object. For instance all you need to provide for your schema at a minimum is:

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

If you tried to do something like,

endDate: null

this will fail as it is expecting a Date() object or nothing at all.

Solution 2:[2]

As you have mentioned that you are storing endDate as null as String. That will definitely fail because your schema expecting a date and you are storing String.

Multiple ways you can approach:

  1. Avoid endDate from JSON object. (You will not have endDate key in MongoDB)
  2. set endDate: undefined that will automatically be ignored. (You will not have endDate key in MongoDB)
  3. Set endDate: null not in String (You will have endDate key as null value)

Below one will not work:

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

But this one will definitely work:

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

Tested on below version:

MongoDB v3.2.18
Mongoose v4.10.8

Another point I want to add here is storing key: null will consume resources. If your requirement is not dependent on null values, I would like to use not to store a key in the database rather storing as null.

Solution 3:[3]

I have solved this by setting the default date to undefined. It will not show up on creation of your object. That is fine as it is now a frontend problem. If a key does not exist the frontend will default to undefined. If it remains undefined it will not be saved in your database. Avoid having a default null I have made that mistake too!

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

Solution 4:[4]

In your schema you can mention the type as endDate : { type: Date || null} and wherever you feel like assign the value as null if date is not there OR you can even add default as null to schema.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Michelangelo
Solution 4 Utkarsh