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

I have a scheme like this:

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

      

Field

permissions

stores an array of strings that looks like this:

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

      

whereas

Field

role

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 store "Show" as the default for the field permissions

in the schema and store "user" as the default for the name inside the roles field, priority 0 for priority

inside the field role

and "Show" for permissions

inside the field role

.

After trying, 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 default values ​​to all fields and gives the fields a size of 0.

What is similar to the diagram above? How do I save them as defaults?

+3


source to share


2 answers


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

Therefore, the array is always initialized as "empty", unless, of course, you intentionally nest something in it. To do what you want to achieve, add a pre save hook that checks for an empty array and then puts in a default otherwise:

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 a value where empty:

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

      

If you are of course initializing your data or manipulating to create an entry in the array:

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

      



Then you get the added array:

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

      

And if you want to "always" have "Show" present in the permissions, then a change like this on the hook can provide that for you:

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

  next();
});

      

Result:

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

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

      

These are ways to manage the default values ​​for the entries in your array without having to explicitly assign them in code using the model.

+13


source


You can add default array values ​​to mongoose this way -



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

      

+1


source







All Articles