1

I can't find a way to edit nested data more than on 2nd level. I have next model structure:

var Category = new Schema({
    name: String,
    url: String,
    id: String
});

var Subgroup = new Schema({
    name: String,
    url: String,
    id: String,
    categories: [Category]
});

var Group = new Schema({
    name: String,
    url: { type: String, default: '' },
    subgroups: [Subgroup]
});

module.exports = mongoose.model('group', Group);

I need to edit certain Category through the Group model. I tried all possible variations of working with nested arrays but have no result.

Group.findOneAndUpdate({
    _id: req.params.groupId,
    "subgroups.categories._id": req.params.categoryId
}, {
    $set: { 
        "subgroups.categories.$.name": attributes.name 
    }
});
0

1 Answer 1

2

Wait, if you have the categoryId, req.params.categoryId, then you could just do the update like this:

Category.findOneAndUpdate({
    _id: req.params.categoryId
}, {$set: {name: attributes.name}})

But to solve the underlying question with updating nested objects, I would suggest you change your Schemas a bit if this is the type of actions you want to perform. Instead of saving arrays you can store the relationship to the parent in the nested object like this:

var Group = new Schema({
    name: String,
    url: {type: String, default: ''},
})
mongoose.model('Group', Group)

var Subgroup = new Schema({
    group: {type: ObjectId, ref: 'Group'},
    name: String,
    url: String,
    id: String,
})
mongoose.model('Subgroup', Subgroup)

var Category = new Schema({
    subgroup: {type: ObjectId, ref: 'Subgroup'},
    name: String,
    url: String,
    id: String
})
mongoose.model('Category', Category)

Now you can do the update by:

Category.findAndUpdate({
    subcategory: req.params.subcategoryId,
}, ...)

Or:

Subgroup.find({
    group: req.params.groupId,
}, function(err, subgroups) {
    subgroups.forEach(function(subgroup) {
        Category.findAndUpdate({
            subcategory: subgroup._id,
        }, ...)
    })
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.