Mongoose single embedded sub-document default

Mongoose maintainer here, I'd recommend this:

var UserSchema = mongoose.Schema({
  fname: String,
  lname: String,
  permissions: 
    type: UserPermisssionsSchema ,
    default: () => ({}),
  }
});

This will make permissions default to an empty object, with respect to any defaults the UserPermissionsSchema might have. If you set default to UserPermisssionsSchema you might get some bad behavior if one of your properties happens to overlap with a mongoose schema method.


Please try this one

var PerSchema = new mongoose.Schema({
    siteAdmin: {type: Boolean, default: false}
  }); 

var UserSchema = mongoose.Schema({
  fname: String,
  lname: String,
  permissions: { type: PerSchema, default: () => ({}) },
});

Test it with Mongoose v4.4.3

var User = mongoose.model('User', UserSchema);

function setUser() {
    var u = new User({
        fname: 'asa',
        lname: 'dddd'
    });

    u.save(function(err) {
        if (err)
            console.log(err);
        else
            console.log('save user successfully');
    });
}

Result is

{ 
  "_id" : ObjectId("56c68321a548be98198ebb71"), 
  "fname" : "asa", 
  "lname" : "dddd", 
  "permissions" : {
       "_id" : ObjectId("56c68321a548be98198ebb70"), 
       "siteAdmin" : false
       },
   "__v" : 0
}

If you want the default value of permissions is {}. Please try it as below

var PerSchema = mongoose.Schema({
    siteAdmin: {type: Boolean}
}, {_id: false}); 

var UserSchema = mongoose.Schema({
    fname: String,
    lname: String,
    permissions: { type: PerSchema, required: true, default: {} },
}); 

Test

function setUser() {
    var u = new User({
        fname: 'asa',
        lname: 'dddd'
    });

    u.save(function(err) {
        if (err)
            console.log(err);
        else
            console.log('save user successfully');
    });
}

Result is

{ "_id" : ObjectId("56c687427191d54021875fb1"), 
  "fname" : "asa", 
  "lname" : "dddd",
  "permissions" : {  }, 
  "__v" : 0
}

Tags:

Mongoose