Search code examples
node.jsmongodbrediscursor

How to use a mongodb cursor with node.js


Let's say that I have a collection in my database called rabbits. My app uses this database and currently there are multiple users using my app. The users want to see the rabbits one by one; when they start the app they see 1 rabbit and then they press 'next' to see the next one, and so on.

I don't want to query the database every time the user presses next, so I decided to use cursors. I am thinking of creating a simple map data structure (working as a cache) that maps a user to its cursor. So before querying the database again we simply check in the map first.

Is this good practice? should I perhaps use redis here instead?


Solution

  • there are probably a million answers to this question and most would be correct. Just some possibilities:

    1. Of course you can use Redis, and read it from memory.
    2. You can also downgrade a bid use something like node-cache which will have less overhead and simpler to implement.
    3. You can take the cursor --> array ---> JSON and if you are not worried about constant new rabbits (after all rabbits do multiply fast :) -- then you can write the rabbits to a JSON file, and pick up as the client wants to swing through it.
    4. You can of course aggregate your MongoDB Cursor...or have a cron job run every few minutes to create a new Rabbit Pick cursor.

    On and on it goes.

    The critical thing is to match what you decide with the services, memory and cores on your server(s).