user1710825
user1710825

Reputation: 588

Update with mongoose

I need set one object of nested array with a property as "default = true", but I only need one with this property, others must not have this property.

Example:

{
    "_id": "xxxxx",
    "name": "Jmae",
    "desktops": [
        {
           "_id": "xxxxx",
           "name": "Mike",
           "default": true
        },
        {
           "_id": "xxxxx",
           "name": "Aris"
        },
        {
           "_id": "xxxxx",
           "name": "John"
        }
    ]
}

This only set, but dont remove:

 var filter = {
            "_id": platformId,
            "desktops._id": desktopId
        },
        updateParams = {
            "$set": {
                "desktops.$.default": true
            }
        };
    crud.findOneAndUpdate(filter, updateParams, null, callback);

This next code works ok, but its huge:

crud.findByIdNeed(platformId, null, null, function (err, platform) {

    // En caso de error
    if (err) {
        callback(err);
        return;
    }

    _.each(platform.desktops, function (desk, i) {

        if(desk._id.toString() === desktopId){
            platform.desktops[i].default = true;
        }else if(platform.desktops[i].default){
            delete platform.desktops[i].default;
        }

    });

    platform.save(callback);

});

How I can make this better?

Upvotes: 2

Views: 208

Answers (1)

C Blanchard
C Blanchard

Reputation: 1063

Perhaps one alternative is to restructure your schema to have the default desktop as a property in platform where it would reference the _id of the relevant desktop. For example, your schema could look something like:

{
    "_id": "xxxxx",
    "name": "Jmae",
    "defaultDesktop": 1932, // Contains the ID of the relevant desktop
    "desktops": [
        {
           "_id": 1932, // This is your default desktop
           "name": "Mike"       
        },
        {
           "_id": "xxxxx",
           "name": "Aris"
        },
        {
           "_id": "xxxxx",
           "name": "John"
        }
    ]
}

This saves you having to iterate over desktops setting/deleting a default property. You can just change default in one place.

Upvotes: 2

Related Questions