I tried to set a default value in an empty field for a document to be saved in the MongoDB
In my case, this is the mongoose schema
var Distribution = new Schema({
temporalCoverage: {
startDate: {type: Date, default: Date.now},
endDate: {type: Date, default: Date.now}
},
distributionText: String
});
This is the document to save:
"distribution": {
"temporalCoverage": {
"endDate": "",
"startDate": ""
},
"distributionText": "test"
}
In this document, the empty fields are endDate and startDate. The document is saved in mongoDB with null values.
"distribution": {
"temporalCoverage": {
"endDate": null,
"startDate": null
},
"distributionText": "test"
}
I want to save the default value, not null
If a put the field required in the schema, temporalCoverage : { startDate : { type: Date, required: true, default: Date.now }, endDate : { type: Date, required: true, default: Date.now } }
I get the error validation, and the document is no saved it.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ). If you don't want to use this version key you can use the versionKey: false as mongoose.
You need the setDefaultsOnInsert
option
var schema = new Schema({
title: String,
genre: {type: String, default: 'Action'}
});
var Movie = db.model('Movie', schema);
var query = {};
var update = {title: 'The Terminator'};
var options = {
// Create a document if one isn't found. Required
// for `setDefaultsOnInsert`
upsert: true,
setDefaultsOnInsert: true
};
Movie.
findOneAndUpdate(query, update, options, function (error, doc) {
assert.ifError(error);
assert.equal(doc.title, 'The Terminator');
assert.equal(doc.genre, 'Action');
});
see http://mongoosejs.com/docs/defaults.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With