最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't my schema to add default values in mongoose arrays? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Aug 6, 2015 at 4:41 Blakes Seven 50.4k14 gold badges131 silver badges136 bronze badges asked Aug 6, 2015 at 1:16 Simran KaurSimran Kaur 1,1017 gold badges24 silver badges41 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 22

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']
    }
});
发布评论

评论列表(0)

  1. 暂无评论