嵌套数组中的Mongoose更新实例

时间:2015-02-18 21:11:28

标签: mongodb mongoose

在Mongoose中,假设我从MongoDB中提取了一个User对象,并且该用户拥有一组Interests。现在我得到一个用户兴趣的实例。

var user = ...
var interest = ...

... //对兴趣进行一些更改。

如何在DB中的User数组中更新Interest对象(在对其进行一些更改之后)?

修改

这是我目前的代码。它不起作用,也不会出错。

    User.update(
        {
            '_id': user._id,
            'interests._id': interest._id
        },
        {
            '$set': {
                'interests.$.xyzProperty': interest.xyzProperty
            }
        },
        function(err,obj){//some error checking}
    );

1 个答案:

答案 0 :(得分:0)

如果您为每个兴趣设置了一个if,您可以通过$运算符访问兴趣。

user document
{
    _id: ObectId('54b568531ef35a7c348f21f2'),
    interests: [
        {
            _id: 12345,
            title: 'Tacos',
            description: 'I Love tacos'
        },
        {...},
        {...},
    ]
}

如果我知道要更新哪个兴趣子文档,我只需查询它:

UserModel.find({_id: ObectId('54b568531ef35a7c348f21f2'), 'interests.i_d': 12345}).lean().exec(function (err, user) {

    var interest =  ... //find specific interest
    interest.description = 'I love tacos... Like, a lot'.

    UserModel.update(
        {
            _id: user._id, 
            'interests._id': interest._id
        },
        {
            $set: {
                'interests.$.description': interest.description
            }
        },
        function (err, update) {
           console.log(err, update);
        }
    );
});

这使用$ position运算符并更新特定的子文档(或数组中的项目)。

相关问题