@mongod/client v0.0.9
@mongod/client
A small but awesome wrapper around the native mongodb driver for Node.js
This library fixes two problems I have with the native driver. Verbosity of connections, and id generations.
Connect
Connections to mongodb are established when they're needed. Lazily. You don't need to handle this yourself, it's handled for you.
import db from '@mongod/client';
await db.comments.insertOne({ body: 'hi!' });
Now, if you're working with a script and needing to close the connection, db
has a method for that:
await db.close();
Now in case you do want to connect explicitly, for the purpose of warming up the connection instead of waiting for the first db hit, it is still possible to do so:
await db.connect();
The connection string is taken from process.env.MONGO_URL
and defaults to mongodb://localhost:27017
.
_id generation
We use picoid
as pkFactory
, and have hot-patched the native driver to add support for bulk operations as well.
In addition to the native driver, it's possible to configure id prefixes per collection. Note that separators are not automatically added! It's for you to decide if you want to use prefixes, and if you want to include a separator, and if so, which character it should be.
db.customers.pkPrefix = 'cus_';
db.customers.insertOne({ name: 'Stephan' });
// customer._id is now cus_vsrd…
How it works
This library wraps the native mongo driver, and adds a few restrictions to it. Let's talk about those.
Every collection method, now returns a promise. We dropped support for the callback style, and unlike the native driver,
collection.initializeOrderedBulkOp
andcollection.initializeUnorderedBulkOp
return promises as well.We wrap the
db
object to get a mongo shell kind of feeling, where you don't need to writedb.getCollection('test').insert
but can simply calldb.test.insert
. This does mean that some names should not be picked as collection name as those will result in name conflicts. The reserved ares
,serverConfig
,bufferMaxEntries
,databaseName
andclose
. I believe that's manageable.We've added a
close
handler to thedb
, which proxiesclient.close
. Just for developer convenience.We also use
picoid
to generate string based random ids. The Mongo ObjectID has its good side, but it makes id handling and parsing quite verbose. Strings are easier to work with. As MongoDB didn't feel for fixing theirpkfactory
to support custom id's in bulk upserts because "It would deviate from other drivers that do not have this behavior"_, we've patched that in this library.