Mongoose: Set default value in a required field when this is not present in the document to save
19,297
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
Related videos on Youtube
Author by
user1783933
Updated on September 15, 2022Comments
-
user1783933 over 1 year
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. -
Nadav over 5 yearsThe
new
option is not a valid option for the Mongooseupdate()
operation and is not needed. Setting theupsert
option totrue
is enough to guarantee that Mongoose will create a new document if one doesn't already exist.