Reputation: 88
I am using the 'mongodb' NPM module in small web server.
I'm wondering whether I should always call db.collection('') on every request that hits the server, or should I rather init a (singleton) collection after I established the db connection, and use the same collection for all requests?
Especially since I have the collection at hand during initialization, to set a unique index, it is pretty tempting to just keep this collection reference and re-use it in all http request handlers.
Could I run into awkward concurrency issues, say, if multiple requests at nearly the same time operate on exactly the same collection instance?
Upvotes: 0
Views: 178
Reputation: 60092
It doesn't matter much, use whichever is easier.
Collections in MongoDB are created lazily, so db.collection(...)
doesn't really do anything itself, only when you use it for something (like query, insert, createIndex, etc.). So it is not an expensive thing to make on each request.
The MongoDB javascript client API does not have any issues with concurrent requests even with the same collection object; it is designed specifically for that scenario.
I would lean towards a single collection since it is slightly less work.
Upvotes: 1