Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

The following is my schemas for the document named 'Folder':

var permissionSchema = new Schema({

    role: { type: String },

    create_folders: { type: Boolean },

    create_contents: { type: Boolean }

});

var folderSchema = new Schema({

    name: { type: string },

    permissions: [ permissionSchema ]

});

In my CMS there's a panel where I have listed all the folders and their permissions. The admin has access to edit single permission and save it.

But I don't want to save all the document so for that I implemented the following code:

savePermission: function (folderId, permission, callback) {

    Folder.findOne({ _id: folderId }, function (err, data) {

        var perm = _.findWhere(data.permissions, { _id: permission._id });                

        _.extend(perm, permission);

        data.markModified("permissions");

        data.save(callback);

    });

}

But the problem is that my 'perm' variable is always unclear. I just want to know how to get the subdocument of a fetched document?

1 Answer

0 votes
by (108k points)

Note that there is a fault in mongoose that is that when you "embed" data in an array(as you have done), you get an _id value for each array record as part of its individual sub-document properties in MongoDB. And the main thing is that you can use this value for determining the index of the item that you want to update. Refer to the code for the implementation:

Folder.findOneAndUpdate(

    { "_id": folderId, "permissions._id": permission._id },

    { 

        "$set": {

            "permissions.$": permission

        }

    },

    function(err,doc) {

    }

);

Related questions

0 votes
0 answers
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...