繁体   English   中英

使用Mongoose在MongoDB中更新文档中数组的元素

[英]Update an element of an Array in a Document in MongoDB with Mongoose

我有一个具有以下结构的MongoDB数据库:

 {
    "_id" : ObjectId("5b670eefe94672265ca59428"),
    "duration" : {
        "start" : ISODate("2018-09-01T00:00:00.000Z"),
        "end" : ISODate("2018-09-01T00:00:00.000Z")
    },
    "title" : "Example title.",
    "description" : "<p>Hi example!</p>",
    "slug" : "title",
    "insertDate" : ISODate("2018-08-05T14:51:27.194Z"),
    "webData" : [ 
        {
            "_id" : ObjectId("5bb1f082931c536950ade361"),
            "webCode" : "be_mx",
            "categories" : [ 
                {
                    "_id" : ObjectId("3sdf43f34543et35tret435"),
                    "name" : "Category 1",
                    "webCode" : "be_mx",
                    "slug" : "category-1"
                },{
                    "_id" : ObjectId("3sdf43f34543et35tretert"),
                    "name" : "Category 2",
                    "webCode" : "be_mx",
                    "slug" : "category-2"
                }
            ]            
        }
    ],
    "__v" : 6,
    "lastEditionDate" : ISODate("2018-10-01T10:01:38.889Z")    
}

我想更新此集合中所有具有_id =“ 3sdf43f34543et35tret435”类别的文档(在本示例中为“类别1”),并且我想将此元素类别设置(例如,从slug)更新为“ category- 3“。

我试图用下面的代码做到这一点:

Collection.update({
            "webData.categories": {
                    $elemMatch: {
                        _id: ObjectId("3sdf43f34543et35tret435")
                    }
                }
            }, {
                $set: {
                    webData: {
                        "categories.$.slug": "category-3"
                    }
                }
            }, {
                multi: true
            }, (err, res) => {
                if (err) { console.log(err); }
                console.log(res);
            });

当我执行该操作时,所有具有该类别的文档都被编辑,但是这是错误的,因为所有相关类别都被删除了。

您可以协助我进行这项作业吗?

谢谢!

编辑:

当我在数据库中执行此查询时:

db.getCollection("scholarships").update({}, 
{ '$set': { 'webData.[].categories.$[category].slug': "nana" } }, 
{ multi: true, arrayFilters: [{ 'category._id': ObjectId("5b719d821f3f1131ec4524f6") }] })

在这段时间内使用arrayFilter,我收到此错误:

文件中必须存在路径'webData。[]。categories'才能应用数组更新。”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM