0

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!

ishahak
  • 6,585
  • 5
  • 38
  • 56
  • You can first of all group all the users (in set) by message id. Then use mongo Unordered Buik operation to execute the queries in a batch. Doing so it will ensure that no two queries will modify the same document – Amit Phaltankar May 05 '17 at 02:46
  • Thank you for the response. Each user is calling my server asynchronously, so I can't group them together before updating – ishahak May 05 '17 at 02:50
  • 1
    Depending upon how frequently you get called by different users. If it's heavy traffic where you have to continuously keep on updating DB then consider executing a single bulk operations in every 30s or 1 min. – Amit Phaltankar May 05 '17 at 02:56

0 Answers0