首页 > 解决方案 > ArrayFilter updateMany 查询在控制台中有效,但无法与 mogoose 一起使用

问题描述

我使用的是 mongoose 版本 5.11.12,我的 mongo 集群运行的是 4.4.3,最后我的节点是:10.19.0。

当我尝试这个查询时:

Group.updateMany({},
    {$push:{"threads.$[elem].messages":"hello"}},
{multi:true ,arrayFilters:[{"elem._id":"602645582fa6cb13f8449057"}]},
    (err,result) =>{
        if(err)res.json({error:err}); else res.json({result:result});
        
    }
)

它对数据库没有任何作用,然后只返回一个无用的错误对象{}

但是,当我直接在 mongo 控制台中运行等效查询时:

db.groups.updateMany({},{$push:{"threads.$[elem].messages":"hello"}},{multi:true ,arrayFilters:[{"elem._id":ObjectId("602645582fa6cb13f8449057")}]})

以及预期的回应:

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 1 }

起初,我认为这可能是 ObjectId 转换的问题,但我弄乱了 objectId,因此它不再是有效的对象 ID,并且它给出了预期的 objectId 错误,因此似乎不太可能是导致问题的原因。

如果有帮助,这就是我的数据库的相关部分的样子:

{
    "_id" : ObjectId("60264286f5440e114c189212"),
    "members" : [ ],
    "name" : "Computer Science London",
    "location" : {
            "coordinates" : [
                    51.503391,
                    -0.12763
            ],
            "_id" : ObjectId("60264286f5440e114c189213"),
            "type" : "Point"
    },
    "description" : "A group for computing students to learn, talk and share!",
    "pictureURL" : "/images/computer.jpg",
    "threads" : [
            {
                    "_id" : ObjectId("602645582fa6cb13f8449057"),
                    "title" : "What is a lambda function",
                    "openingPost" : "I am reading this textbook and it mentions this thing called a lambda function, but it doesnt seem to outline what it is. Can someone help me understand?",
                    "postedBy" : "ElBarto88",
                    "updatedAt" : ISODate("2021-02-12T09:07:36.833Z"),
                    "createdAt" : ISODate("2021-02-12T09:07:36.833Z"),
                    "messages" : [
                            "hello"
                    ]
            },
            {
                    "_id" : ObjectId("602645af2fa6cb13f8449058"),
                    "title" : "How do i install linux?",
                    "openingPost" : "This server assignment requires i have linux installed, how do install it?",
                    "postedBy" : "ElBarto88",
                    "updatedAt" : ISODate("2021-02-12T09:09:03.123Z"),
                    "createdAt" : ISODate("2021-02-12T09:09:03.123Z"),
                    "messages" : [ ]
            }
    ],
    "createdAt" : ISODate("2021-02-12T08:55:34.273Z"),
    "updatedAt" : ISODate("2021-02-12T09:09:03.123Z"),
    "__v" : 0

}

标签: javascriptmongodbexpressmongoose

解决方案


推荐阅读