Thursday 4 May 2017

Mongodb: updating multiple docs in a loop?

I did a great effort to find a solution to this common situation, without success. Hoping somebody can help please.

Background:

  • A board of messages.
  • Each message has its msg_id.
  • Each user has an id
  • I need to track which user watched which message. For this I have a collection called viewedMessages like this:
    {
        { _id: <message_id_X>,
            viewedBy: [<user_id_?>,<user_id_?>,...]
        },
        { _id: <message_id_Y>,
            viewedBy: [<user_id_?>,<user_id_?>,user_id_?>,...]
        },
        ...
    }

The user is calling my node.js server once in a while, reporting which messages were viewed, like this:

{ user_id: <user_id_?>, viewed: [<message_id_?>,...] }

An entry for a message is only created when some user is reporting it as viewed. This is done using this command:

db.viewedMessages.update({"_id":<msg_id>},{$addToSet:{viewedBy:<user_id>}},{ upsert : true });

Now for the question.

The above update command is asynchronous. How do I run over an array of [msg_id,msg_id,msg_id,...], issuing the above update command for each msg_id, and finally get a callback telling me that everything was done ok OR failed for some reason?

Would highly appreciate any help here!



via ishahak

No comments:

Post a Comment