Mongodb Update Multiple array objects at once

时间:2019-03-17 22:56:41

标签: javascript mongodb mongoose

Im trying to enter every family Documents, and on each of those documents, Check if theres a user in the users array (user is an object) that matching the results, and then update the spesific one.

How would i accomplish so the query would go trough documents, and in every users, if matched criteria, update it?

First attempt code:

            var From_joinedTime = new Date().getTime() - (60*60*24*2*1000);

   return Family.updateMany({"users.permission" : 0, "users.joined_date" : {$lte: From_joinedTime}},{$set: {"users.$.permission" : 1}},{multi:true}).then(function (response) {
                    return response;
                });

Please note:

i tried to Google, and came over the same issue, and tried the answer by Neil Lunn there: How to Update Multiple Array Elements in mongodb

Code modified from Neil Lunn:

Family.update(
                { "users.permission":0, "users.joined_date":  {$lte: From_joinedTime}},
                { "$set": { "users.$[elem].permission": 1 } },
                { "arrayFilters": [{ "users.permission": 0,
                        "users.joined_date":  {$lte: From_joinedTime} }], "multi": true }
            )

But that failed.

i found this question that had same issue, but i could not find the answer good enough: Cannot read property 'castForQuery' of undefined at castArrayFilters in Node.js

Error:

(node:9740) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'castForQuery' of undefined
at castArrayFilters (\node_modules\mongoose\lib\helpers\update\castArrayFilters.js:60:37)
at _castArrayFilters (\node_modules\mongoose\lib\query.js:1736:5)
at model.Query._updateThunk (\node_modules\mongoose\lib\query.js:3449:3)
at model.Query.<anonymous> (\node_modules\mongoose\lib\query.js:3535:23)
at model.Query._wrappedThunk [as _execUpdate] (\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
at process.nextTick (\node_modules\kareem\index.js:369:33)
at process._tickCallback (internal/process/next_tick.js:61:11)

What do i do?

1 个答案:

答案 0 :(得分:0)

请尝试以下查询:-

Family.update(
                { "users.permission":0, "users.joined_date":  {$lte: From_joinedTime}},
                { "$set": { "users.$.permission": 1 } },
                { "multi": true }
            )

位置运算符$将负责更新数组中匹配的用户。