Search code examples
mongodbmongooseupdatesmongoose-schemaauto-update

Mongoose set default on field update if field is not present or null


I have a mongoose schema like this suppose:-

var mSchema = new Schema({
  name: { type: String, required: true}
});

and have been using this schema for a year and now i want to add gender to it like this :-

var mSchema = new Schema({
  name: { type: String, required: true},
  gender: { type: String, default: 'Male' } 
});

whenever there will be an update request i want this gender to automatically set Male as default but i found that default don't set on update request. (Note: It's just an example not a real life scenario. i just want mongoose default work if field is not present or null)

Is there any way in which i can set default on the updation of document ?


Solution

  • If you are using a function like update(), then this is not directly possible as stated by this answer. Still, you can simply switch to a function like findOne() and use save(), which should do the same.

    When upserting documents, you can also check out the setDefaultsOnInsert option: https://mongoosejs.com/docs/defaults.html#the-setdefaultsoninsert-option

    const options = {
      // Create a document if one isn't found. Required
      // for `setDefaultsOnInsert`
      upsert: true,
      setDefaultsOnInsert: true
    };
    
    await XY.findOneAndUpdate(query, update, options);