-1

Suppose I have a new club created by a user and this user has chosen many users as the members of the club. so after creating the club I should find all the members and add club._id to their clubs field. like so

await User.updateMany({_id : {$in: newClub.members}}, {clubs: [...user.clubs, newClub._id]});

Notice! the user.clubs is an imaginary variable that I need.

I was wondering if there is a way I can push the new club to their existing clubs without looping over them and pushing club._id to their clubs field and saving them. Thanks

That's right that in this case I aim to use push on an existing document, but my question differs from Push items into mongo array via mongoose since I generally want to know how to access a field from an existing document when updating it.

Reza Shoja
  • 887
  • 2
  • 11
  • 24

1 Answers1

0

You can use MongoDB aggregation pipeline to push the new value to the array

User.updateMany(
    {_id : {$in: newClub.members}}, 
    { $push: { clubs: newClub._id } },
    function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
);
thuva4
  • 1,185
  • 8
  • 13