Skip to content

@jsmrcaga mongo

Jo Colina edited this page Apr 18, 2020 · 2 revisions

MMTB is a very simple MongoDB driver wrapper, adding some easy-to-understand and powerful interfaces.

Installation

Install using npm:

npm i @jsmrcaga/mongo

Connecting to your DB:

To create your DB definition you should create a new file. This will come in handy later on when we create models and write tests:

const { Database } = require('@jsmrcaga/mongo');

const database = new Database('main', {
	username: process.env.DB_USERNAME,
	password: process.env.DB_PASSWORD,
	endpoint: process.env.DB_ENDPOINT,
	port: process.env.DB_PORT,
	database: process.env.DB_DATABASE,
	useUnifiedTopology: true
        ...anyOtherOptionsMongoDriverUnderstands
});

module.exports = database;

In order to connect, simply call:

const DB = require('./mydb.js');

DB.connect().then().catch();

Models

Models are represented as classes in MMTB. This allows you to write very clear models. Please note that no validation is performed. You can perform validations thanks to Mongo's API.

Models automatically implement some fields:

  • __created: Date when the object was created
  • __deleted: Soft-delete by default, and stores the deletion date
  • __updated: Last update date

To create a model you will need a link to the DB it's from:

const DB1 = require('./mydb1');

const MyModelBase = DB1.model('Name of your model');

class MyModel extends MyModelBase {
    constructor({ a, b, c }) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    myMethod() {}
}

These models proxy the Collection model from Mongo's Driver. This means that any static function not defined by MMTB or Yourself will be looked for in the Collection object and used if found.

Model static Methods

Please note that whenever you see options, they will be forwarded as-is to the underlying Mongo Collection method.

Model#name()

Returns the collection name, lower cased. Mongo compares collection names lowercased, be mindful of that when using aggregation and other tools.

MyModel.name()

Model#collection()

Returns the corresponding Mongo Collection object.

Model#all(options={})

Returns a cursor looking for all non-deleted objects { __deleted: false }:

MyModel.all().skip(50).limit(50).toArray().then(my_objects => {})

Model#get(selector={}, options={})

Gets a single instance of your model, already instanciated.

MyModel.get({ id: 54 }).then(myModel => myModel.doSoMething());

Model#find(selector={}, options={})

Finds models. If __deleted is not present in selector it will be added as { __deleted: false } in order to allow you to write simple queries.

Returns a Cursor.

  • Alias: MyModel.filter()
MyModel.find({ brand: 'Toyota' }).skip().limit()

Model#insertMany(objects, options={})

Inserts many objects to the DB in one query. Verifies that all objects are instances of the class.

let objs = [myobj1, myobj2, myobj3];

MyModel.insertMany(objs).then().catch()

Model#updateMany(objects, options={})

Updates many objects to the DB in one query. Verifies that all objects are instances of the class.

let objs = [myobj1, myobj2, myobj3];

MyModel.updateMany(objs).then().catch()

Model#delete(objects, options={})

Deletes many objects to the DB in one query by setting __deleted to the current date. Verifies that all objects are instances of the class.

let objs = [myobj1, myobj2, myobj3];

MyModel.delete(objs).then().catch()

Model#createIndex(index, options)

Creates an index in your collection. index must be formatted as per the (reference)[https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#createIndex].

MyModel.createIndex({ name: 1 }).then().catch()

Model#createIndexes(indexes, options={})

This method can be called in 2 ways:

Bulk

Calls Collection().createIndexes

MyModel.createIndexes([i1, i2, i3], { bulk: true });
One-by-one

Calls Collection().createIndex

MyModel.createIndexes([{ ...def1, options:{ ...options1 } }, { ...def2, options:{ ...options2 } }])

Model Instance Methods

Model.save(options={})

Saves or updates a model in the collection

const model = new MyModel({});

model.save().then().catch()

Model.update(data={})

Updates the reference of the model with the new data

const model = new MyModel({ name: 'Plep' });

model.update({ name: 'Plop' });
console.assert(model.name === 'Plop');

Model.delete(options={})

Delete a single model from the collection by setting __deleted to the current data

const model = new MyModel({});

model.delete().then().catch()

Model.remove(options={})

Removes a single model from the collection. Equivalent to hard-deletion

const model = new MyModel({});

model.remove().then().catch()