Ryan
Ryan

Reputation: 1019

Updating two different documents in one line

I have the following code for updating two users, both with different id .

User.update(
    { id: req.body.myId }, 
    {
        $addToSet: { FriendIds: req.body.friendId }
    }, 
    function(err, user){

    }
);

User.update(
    { id: req.body.friendId }, 
    {
        $addToSet: { FriendIds: req.body.myId }
    }, 
    function(err, user){

    }
);

I could not find anything in the docs aside from updating two things with the same attribute by setting multi : true . However, the ids are different in this case, and it would be easier to error handle if I had them both being updated at once.

Upvotes: 0

Views: 29

Answers (1)

J.Arturo Covarrubias
J.Arturo Covarrubias

Reputation: 176

Why not take advantage of parallel operations in bluebird or using co

You can do something like :

co(function* () {
  var res = yield {
    1: User.update({ id: req.body.myId }, { $addToSet: { FriendIds: req.body.friendId }}).exec(),
    2: User.update({ id: req.body.friendId },{$addToSet: { FriendIds: req.body.myId }}).exec(),
  };
  console.log(res); // { 1: Upate_response_for_1 , 2: Upate_response_for_2 } 
}).catch(onerror); 

Upvotes: 1

Related Questions