编辑3级mongo上的数据

时间:2013-12-27 11:40:33

标签: node.js mongodb mongoose

我找不到比第二级更多编辑嵌套数据的方法。 我有下一个模型结构:

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);

我需要通过群组模型修改某些类别。我尝试了使用嵌套数组的所有可能变体但没有结果。

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

1 个答案:

答案 0 :(得分:2)

等等,如果你有categoryId,req.params.categoryId,那么你可以像这样进行更新:

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

但是要解决更新嵌套对象的基本问题,如果这是您要执行的操作类型,我建议您稍微更改一下Schema。您可以将关系存储在嵌套对象中,而不是保存数组,如下所示:

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)

现在您可以通过以下方式进行更新:

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

或者:

Subgroup.find({
    group: req.params.groupId,
}, function(err, subgroups) {
    subgroups.forEach(function(subgroup) {
        Category.findAndUpdate({
            subcategory: subgroup._id,
        }, ...)
    })
})