0
votes

I have the following document structure and need to add to a sub-subdocument using mongoose:

var organization = module.exports = mongoose.Schema({
    teams: [{
                permissions: [{ permission: String }]
    }]
})

organization.methods.addTeam = function(team){
    //the save occurs in a repository layer later on, for now I am just prepping the object for the save
        this.teams.push(team);
        var subdoc = this.teams[0];
        subdoc.isNew;
}

//Ideally, something like this would be great but I have not been able to find any doc that really provides a good example on this scenario
organization.methods.addPermission = function(id(team), permission){
    var teams = this.teams.id(id)
    teams.permissions.push(permission);
    var subsubdoc = teams.permission[0];
    subsubdoc.isNew;
}

I am a newbie to node.js and mongodb and am running into the following issue with sub-subdocuments. In the following example, I need to add to the permissions array. I added a new method on the organization schema to handle adding the team to the organization as per an example I found. I would like to add a similar method to the organization schema to handle adding permissions to the team subdocument. I also would like to check and make sure the permission does not already exists before adding as well. How should I handle this scenario?

1

1 Answers

0
votes

Take a look at MongoDB's $addToSet operator.

// file: modules/organization/add_permission.js

var Organization = mongoose.model('Organization');

exports.addPermission = function(teamId, permission) {

  Organization.update(
    {_id: teamId}, // query
    {$addToSet: {permissions: {permission: permission}}}, // update
    function(err) { // callback
       // handle error
       // other logic
    }
  );
};

Or do something similar as a method on your Organization mongoose model.