0.0.9 • Published 4 years ago

@mongod/client v0.0.9

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

@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.

  1. Every collection method, now returns a promise. We dropped support for the callback style, and unlike the native driver, collection.initializeOrderedBulkOp and collection.initializeUnorderedBulkOp return promises as well.

  2. We wrap the db object to get a mongo shell kind of feeling, where you don't need to write db.getCollection('test').insert but can simply call db.test.insert. This does mean that some names should not be picked as collection name as those will result in name conflicts. The reserved are s, serverConfig, bufferMaxEntries, databaseName and close. I believe that's manageable.

  3. We've added a close handler to the db, which proxies client.close. Just for developer convenience.

  4. 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 their pkfactory 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.

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago