Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...