Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a schema like this:

var CustomUserSchema = new Schema({
    role: [],
    permissions: [],
});

permissions field store an array of strings that looks like this:

["Delete", "Show","Create"]

whereas

role field stores an array of objects that looks like this:

[
    {
        name:"admin",
        priority:10,
        permissions: ["Delete", "Show" , "update"]
    },
    {
        name:"user",
        priority:5,
        permissions: ["Delete", "Show"]
    }
]

Now, my requirement is to be able to store "Show" as default value for permissions field in the schema and to store 'user' as default value for name inside of role field , priority 0 for priority inside of role field and 'Show' for permissions inside of role field.

Trying myself, I came up with this:

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

But it does not assign the default values to the fields at all and gives an array of size 0 to the fields .

What seems wrong with above schema? How do I store these as default values?

like image 491
Simran Kaur Avatar asked Aug 06 '15 01:08

Simran Kaur


1 Answers

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.

like image 75
Blakes Seven Avatar answered Oct 12 '22 23:10

Blakes Seven