Why doesn't my schema to add default values in mongoose arrays? Why doesn't my schema to add default values in mongoose arrays? mongoose mongoose

Why doesn't my schema to add default values in mongoose arrays?


Default values really don't work with arrays, unless of course it is a document within the array and you want to set a default property for that document when added to the array.

Therefore an array is always initialized as "empty" unless of course you deliberately put something in it. In order to do what you want to achieve, then add a pre save hook that checks for an empty array and then otherwise places a default value in there:

var async = require('async'),    mongoose = require('mongoose'),    Schema = mongoose.Schema;mongoose.connect('mongodb://localhost/authtest');var userSchema = new Schema({  permissions:[{    "type": String,    "enum": ["Delete","Show","Create","Update"],  }]});userSchema.pre("save",function(next) {  if (this.permissions.length == 0)    this.permissions.push("Show");  next();});var User = mongoose.model( 'User', userSchema );var user = new User();user.save(function(err,user) {  if (err) throw err;  console.log(user);});

Which creates the value where empty:

{ __v: 0,  _id: 55c2e3142ac7b30d062f9c38,  permissions: [ 'Show' ] }

If of course you initialize your data or manipulate to create an entry in the array:

var user = new User({"permissions":["Create"]});

Then you get the array you added:

{ __v: 0,  _id: 55c2e409ec7c812b06fb511d,  permissions: [ 'Create' ] }

And if you wanted to "always" have "Show" present in permissions, then a similar change to the hook could enforce that for you:

userSchema.pre("save",function(next) {  if (this.permissions.indexOf("Show") == -1)    this.permissions.push("Show");  next();});

Which results in:

var user = new User({"permissions":["Create"]});{ __v: 0,  _id: 55c2e5052219b44e0648dfea,  permissions: [ 'Create', 'Show' ] }

Those are the ways you can control defaults on your array entries without needing to explicitly assign them in your code using the model.


You can add default array values in mongoose this way -

var CustomUserSchema = new Schema({    role: {        type: Array,         default: {            name: 'user',             priority: 0,             permissions: ['Show']        }    },    permissions: {        type: [String],         default: ['Show']    }});