Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Set default value in a required field when this is not present in the document to save

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.

like image 441
user1783933 Avatar asked Feb 21 '17 17:02

user1783933


People also ask

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What does save () do in Mongoose?

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.

What is required true in Mongoose schema?

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.

What is __ V 0 in Mongoose?

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.


1 Answers

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

like image 73
Maxwell s.c Avatar answered Sep 17 '22 08:09

Maxwell s.c