Search code examples
node.jsmongodbmongoose

Mongoose update document with $or condition


I would like to search for all activity which has the same action_object.reply.id or action_target.reply.id. Something like this:

Activity
  .find({ $or: [
    { 'action_object.reply.id': replyId }, 
    { 'action_target.reply.id': replyId }
  ]});

But i also only want to update the removed attribute like this:

Activity
  .update({ 'action_object.reply.id': replyId }, {
            'action_object.reply.removed': true }, { multi: true });

Activity
      .update({ 'action_target.reply.id': replyId }, {
                'action_target.reply.removed': true }, { multi: true });

Is it possible to somehow combine these two queries? I want to update action_target.reply.removed where action_target.reply.id or action_object.reply.removed where action_object.reply.id.

Or i must write two different queries for this like i did above.


Solution

  • The first argument to the update call is the query object, so you can simply use the same $or query. Mongo will update all documents retrieve by the query.

    Activity
      .update({ $or: [
        { 'action_object.reply.id': replyId }, 
        { 'action_target.reply.id': replyId }
      ]}, {'action_object.reply.removed': true }, { multi: true });