npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@jsmrcaga/mongo

v1.1.0

Published

MongoDB as it was Meant To Be (mmtb)

Downloads

38

Readme

Mongo as it was meant to be

The idea beahing this package is to leave the developer as much freedom as possible, while still providing some utility methods to use in Mongo.

In this package models depend on the DB connection, enabling you to have multiple connections, and allowing for model handling without being concerned by the DB location.

Exports

This module exports Database and ModelFactory properties in an object:

module.exports = { Database, ModelFactory };

tl;dr

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

const myDB = new Database('test-db', {
	username: 'test-user',
	password: 'mypassword',
	endpoint: 'localhost',
	port: 46037,
	database: 'test-db'
});


const UserModel = myDB.model('User');

// can also be defined as
// const UserModel = ModelFactory(myDB, 'User');

class User extends UserModel {
	constructor(name, lastname) {
		super();
		this.name = name;
		this.lastname = lastname;
	}
}

const me = new UserModel();
me.name = 'Test';
me.lastname = 'User';
await me.save();

const brother = new User('Brother', 'User');
brother.save();

const Account = myDB.model('Account');

const account = new Account();
account.user = me.id;
await account.save();

let [myAccount] = await me.related(Account);

let annotatedMe = await me.annotate(Account);
assert(annotatedMe.account.id === account.id);

let [myself] = await User.get({id: me.id});
let allOfUs = await User.all();

allOfUs = allOfUs.map(person => {person.age = Math.random() * 100; return person;});

await User.updateMany(allOfUs);

let allOfThem = allOfUs.map(me => reverse(me));
await User.insertMany(allOfThem);

// coming in the next weeks
let [myFacebookAccount] = Account.query('type=facebook (user=54 or name="Test") token_expired=false');

// CONNECTION
myDB.connect({
	protocol, 
	endpoint, 
	username, 
	password,
	port, 
	database,
	timeout, 
	...mongoUsualConnectionOptions
});

API

Database

The Database object represents a Database connection. It will also expose a function to create models that depend on it.

constructor(name, [options])

Creates a new Database object. You should give it a name.

options is an Object containing connection options that will be passed to Mongo Driver:

 options = {
 	protocol,
 	endpoint,
 	username,
 	password,
 	port,
 	database,timeout
}

connected()

true if the database is connected to a Mongod instance, false otherwise

model(name, [options])

Creates a new model on this Database instance

name is a string giving the name of the object.

let UserModel = database.Model('User');

This will create a collection on the database with the model's name lowercased. If you would like the collection to be plural, set the model name to plural.

Returns Class

connect([options])

Connects to mongod instance

options is a connection options Object that will be passed to Mongo Driver. It is not needed if the database object was instanciated with them. Otherwise it will override them.

disconnect()

Disconnects from database

Returns Promise

clear()

Clears the database (deletes all collections) Returns Promise

ModelFactory(database, model_name, [model_options])

Creates a model for the given database instance and for given name.

model_options is an object. Unused for now.

Model

Represents a model on the database. When retrieving objects they will be instanciated to this class.

constructor()

By default the constructor for a created model has a length of 0 (ie: it has no parameters); If you add parameters this driver will pass the received object from database as 1st parameter to the constructor.

The only property set by this constructor is .id. If you override it, please do it carefully.

If you would like to override this behaviour please refer to static fromJSON(obejcts);

static name()

Returns the name of the current object (in LowerCase);

Returns string

static all()

Gets all objects from this model (ie: collection) from the database Returns Promise

static get(selector = {})

Gets objects related to the given selector (Mongo selector). If no selector is passed, defaults to .all().

Returns Promise

static find()

Alias for get()

static collection()

Returns current Collection object related to the model.

Throws if database is disconnected.

Returns Collection

static insertMany(instances)

Inserts many objects to the collection. instances is an array of instances of this object, or object literals containing an id property.

Returns Promise

static updateMany(instances)

Updates many objects (one by one) on the collection. instances is an array of instances of this object, or object literals containing an id property.

Returns Promise

static deleteMany(instances)

Deletes many objects to the collection. instances is an array of instances of this object, or object literals containing an id property.

Returns Promise

static query(querystring)

⚠️ Not supported yet

related(OtherModel, [prop], [myProp])

Fetches related models from another collection.

This method allows you to fetch related objects to the current instance from different collections.

await myUser.related(Car); // --> returns all Car objects related to this user

By default it looks up the current model name as a property on the other collection (ie: car.user), and tries to match it with the current model id: car.user === this.id;

prop overrides the property to look up for in the related model (ex: car.user_id would be myUser.related(Car, 'user_id'))).

myProp overrides the property to check against on the current model (ex: car.user_id === this.car_id, would be myUser.related(Car, 'user_id', 'car_id'))

Returns Promise(objects)

annotate(OtherModel, [ownProp], [params])

Annotates the current model with related objects

This method fetches related objects and annotates current instance with them on ownProp. By default ownProp will be OtherModel.name():

await myUser.annotate(Car) // ==> { id: 'user id', 'car': [<list of related cars>] }

params is an object containing {prop, myProp} that will be passed to Model.related to fetch related OtherModels.

Note that the result is a copy of the current object with the annotated values. If you save it it will override the current model and add the annotated values.

Returns Promise(annotated instance)

save()

Saves the current object to database.

Returns Promise

delete()

Deletes the current object from database

Returns Promise