1

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?

maria
  • 207
  • 5
  • 22
  • 56
  • 1
    Read the answer and documentation again. `{ "arrayFilters": [{ "elem.permission": 0, "elem.joined_date": {$lte: From_joinedTime} }]`. You used `"$set": { "users.$[elem].permission": 1 }` That means `elem` is the name of the **identifier** and not `users`, since that is the name of the actual array. The **identifier** is what is expected and mongoose is throwing the error when it cannot parse and match that missing identifier in the statement. – Neil Lunn Mar 18 '19 at 05:32

1 Answers1

0

Please try this query:-

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

Positional operator $ will take care of updating the matching user inside the array.

cEeNiKc
  • 1,308
  • 7
  • 13