monoxide
A less poisonous way to work with Mongo
Last updated a month ago by hash-bang .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install monoxide 
SYNC missed versions from official npm registry.

Monoxide

A less poisonous to work with Mongo.

Monoxide attempts to provide nicer, chainable functionality on top of base Mongo while making some of the more C centric designs of Mongo more Node like.

NOTE: While Monoxide is now mostly stable there are still likely to be bugs. Please report these to the author if found

  1. API documentation
  2. ReST server
  3. Example setups
  4. Common recipes and design patterns
  5. TODO list
  6. Future ideas
  7. Common issues

Key differences from Mongoose / MongoDB-Core:

  • ReST server - Provides an out-of-the-box Express middleware
  • Syntax - Returns a nicer syntax for specifying schemas
  • Query parameters as arrays - Sort + Populate functionality can now be specified as an array rather than only as space delimited strings
  • Plain objects - All documents are accessible as plain JavaScript objects
  • Virtuals - Virtuals are handled locally (not on the database)
  • Methods - Methods are handled locally (again not on the database)
  • Hooks - Hooks (i.e. Mongoose pre, post calls) actually work as they should. Hooks like all the above are local and not fired at the database level
  • OIDs / ObjectIDs - All pointers (or mongoose.Types.ObjectId as Mongoose refers to them) are strings. Comparison is simple string comparison, there is no need to call .toString() on each object. The function still exists if you want an entirely plain object sans all the glued functions like save()
  • Schemas get applied on each document retrieval. Changing the schema of your project no longer leads to documents having 'the old version'. New fields added to the schema after document creation will be applied to older documents.
  • ReST field surpression - By default all fields prefixed with _ (excepting _id and __v) are removed from ReST server output. This can be changed by adjusting the omitFields setting for monoxide.express.(middleware|query|get.
  • Document mapping - Each output document can be run though the map function to decorate it before it leaves the server - this is useful to omit complex things the client doesn't need or otherwise glue information to the document.
  • Callback error if no matching records - If no matching records are found in a get() operation and $errNotFound is true (the default) Monoxide will populate the error property of the callback. This is useful to automatically abandon Async chains when an expected record is not found rather than having to do manual check for record existence later.
  • Pass private data using $data - The $data object can be specified in any operation (query, save, delete etc.) and is ignored by Monoxide but still passed into hooks. This can be used as a method to pass data to lower-level functions such as logging operations (e.g. pass the currently logged in user to the lower level hooks)
  • Meta polling - Access database meta information using either the meta() method or the ReST adapter
  • Version management - Created documents correctly set the __v property and increment it on save
  • DEBUG compatibility - Setting the environment variable DEBUG=monoxide will output any errors raised by Monoxide to the console

See the ideas list for future ideas.

Schema Setup

Monoxide supports setting the type property via a string instead of using pointers to types within the mongoose.Types structure. Its also really easy to add methods, statics and virtuals using chainable syntax.

var Users = monoxide
	.schema('users', {
		name: String,
		role: {type: String, enum: ['user', 'admin'], default: 'user'},
		favourite: {type: 'pointer', ref: 'widgets'},
		items: [{type: 'pointer', ref: 'widgets'}],
		mostPurchased: [{
			number: {type: 'number', default: 0},
			item: {type: 'pointer', ref: 'widgets'},
		}],
	})
	.static('countByType', function(type, next) { // Adds User.countByType(TYPE, callback) as a model method
		Users.count({
			$collection: 'users',
			role: type,
		}, next);
	})
	.method('splitNames', function() { // Adds UserDocument.splitNames() as a method
		return this.name.split(/\s+/);
	})
	.virtual('password', function() { return 'RESTRICTED' }, function(pass) { // Adds a password handling virtual
		// Replace this with your own impressive password hashing kung-fu
		this._password = pass;
	})
	.hook('save', function(next, doc) { // Adds a hook for when a document is saved (must fire callback to accept changes)
		console.log('User', doc._id, 'has been modified');
		next();
	})

Note that the awkward mongoose.Schema.ObjectId type is replaced with the nicer 'pointer' type specified as a string. All other types can be similarly specified (e.g. "number", "string" etc.).

Schemas are also automatically compiled and returned as an object from monoxide.schema without any need to perform additional actions on the schema before its usable. Functions that declare additional operations such as virtuals, statics, methods, hooks etc can be added and removed at any time without recompiling the object.

ReST Server

The primary interface to Monoxide is the ReST server interface for Express:

var express = require('express');
var monoxide = require('monoxide');

var app = express();

app.use('/api/users/:id?', monoxide.express.middleware({
	collection: 'users',

	get: true, // Allow retrieval by ID
	query: true, // Allow retrieval of multiple records as a query
	count: true, // Allow record counting via query
	create: false, // Alow record creation via POST / PUT
	save: false, // Allow saving via POST / PATCH
	delete: false, // Allow record deletion via DELETE
	meta: false, // Allow retrieval of collection meta information

	// ... other options here ... //
}));

OR you can also bring in only the specific Express middleware thats required:

var express = require('express');
var monoxide = require('monoxide');

var app = express();

app.use('/api/doodads/:id?', monoxide.express.middleware('doodads'));
app.use('/api/widgets/:id?', monoxide.express.middleware('widgets'));

You can also secure the various methods by passing in middleware:

app.use('/api/users/:id?', monoxide.express.middleware('users', {
	get: true, // Allow retrieval by ID
	create: false, // Dont allow record creation
	query: false, // Dont allow querying of users (direct ID addressing is ok though)
	count: false, // Disable counting

	query: true, // Allow retrieval of multiple records as a query

	save: function(req, res, next) {
		// User must be logged in AND be either the right user OR an admin to save user info
		if (
			(req.user && req.user._id) && // Logged in AND
			(
				req.user._id == req.user._id || // Is the same user thats being saved (saving own profile) OR
				req.user.role == 'admin' // User is an admin
			)
		) return next();
		return res.status(403).send('Not logged in').end();
	},

	delete: function(req, res, next) {
		// Only allow delete if the query contains 'force' as a string
		if (req.query.force && req.query.force === 'confirm') return next();
		return res.status(403).send('Nope!').end();
	},
}));

NOTES:

  • Sort keys prefixed with - are inverted. For example sort=-name means 'sort by names in reverse order'
  • Multiple query keys are automatically converted into arrays as a '$in' query type. For example key=val1&key=val2 becomes key={$in:[val1,val2]}. If you do not want this behaviour disable shorthandArrays in the ReST options.

Cherry-picking middleware

You can also pick-and-choose the handlers to be used:

var express = require('express');
var monoxide = require('monoxide');

var app = express();

app.get('/api/users', monoxide.express.query('users'));
app.get('/api/users/count', monoxide.express.count('users'));
app.meta('/api/users/meta', monoxide.express.meta('users'));
app.get('/api/users/:id', monoxide.express.get('users'));
app.post('/api/users', monoxide.express.create('users'));
app.post('/api/users/:id', monoxide.express.save('users'));
app.delete('/api/users/:id', monoxide.express.delete('users'));

In the above the specified models are bound to their respective ReST end points (GET /api/users will return all users for example).

API

Below is the quick-reference API. For more detailed docs see the API documentation for the generated JSDoc output.

Document creation

Create a new document.

	monoxide.create([data], [callback])
	monoxide.models.MODEL.create([data], [callback])
	monoxide.create({
		$collection: 'widgets',
		name: 'My new widget',
	}, function(err, widget) { // ... // });

	monoxide.models.widgets.create({
		name: 'My new widget',
	}, function(err, widget) {
		// widget = newly created document
	});

In addition to regular document key/values the data object can also contain the following meta keys:

Key Type Default Description
$collection String null The collection to create the document in
$refetch Boolean true Whether to refetch the document from the database again after creation

See the create test scripts for more complex examples.

Document finding (single)

Find one document.

monoxide.get([query], [callback])
monoxide.models.MODEL.findOne([data], [callback])

Document finding (multiple)

Find multiple documents.

monoxide.query([query], [callback])
monoxide.models.MODEL.find([query], [callback])

Document counting

Count documents.

monoxide.count([query], [callback])
monoxide.models.MODEL.count([query], [callback])

Document saving (one)

Save data to an existing document.

monoxide.save([data], [callback])
monoxide.models.MODEL.save([data], [callback])

Document saving (multiple)

Save data to multiple existing documents.

monoxide.update([data], [callback])
monoxide.models.MODEL.update([data], [callback])

Document deletion

Delete documents in a collection by an optional query.

monoxide.delete([query], [callback])
monoxide.models.MODEL.delete([query], [callback])
document.delete([callback])

monoxide.remove([query], [callback])
monoxide.models.MODEL.remove([query], [callback])
document.remove([callback])
// Delete a specific document by its ID
monoxide.delete({
	$collection: 'widgets',
	$id: someID,
});

// Delete a specific document by its ID
monoxide.models.widgets.remove({
	$id: someID,
});


// Delete all documents in the collection where color='blue'
monoxide.delete({
	$collection: 'widgets',
	$multiple: true,
	color: 'blue',
});

// Delete all documents in the collection
monoxide.models.widgets.delete();

Notes:

  • Deleting by an empty query (or not specifying the query at all, e.g. monoxide.model.delete()) will throw an error if the monoxide.settings.removeAll flag is true to allow nuking an entire collection.
  • delete and remove functions are interchangable, the other is just provided for convenience

Hooks

Hooks allow watching of models. Each Hook within monoxide accepts a callback that must be triggered for execution to continue.

monoxide.models.MODEL.hook('create', function(next, query) { // ... // });
monoxide.models.MODEL.hook('postCreate', function(next, query, newDoc) { // ... // });

monoxide.models.MODEL.hook('query', function(next, query) { // ... // });

monoxide.models.MODEL.hook('save', function(next, query) { // ... // });
monoxide.models.MODEL.hook('postSave', function(next, query, newDoc) { // ... // });

monoxide.models.MODEL.hook('update', function(next, query) { // ... // });

monoxide.models.MODEL.hook('delete', function(next, query) { // ... // });
monoxide.models.MODEL.hook('postDelete', function(next, query) { // ... // });

Notes:

  • For post* hooks the newDoc parameter will only return the newly created document if $refetch=true within the create or save query. Query will always be present.

Current Tags

  • 0.0.152                                ...           latest (a month ago)

146 Versions

  • 0.0.152                                ...           a month ago
  • 0.0.151                                ...           3 months ago
  • 0.0.150                                ...           6 months ago
  • 0.0.148                                ...           6 months ago
  • 0.0.146                                ...           6 months ago
  • 0.0.144                                ...           6 months ago
  • 0.0.142                                ...           7 months ago
  • 0.0.141                                ...           7 months ago
  • 0.0.140                                ...           8 months ago
  • 0.0.139                                ...           8 months ago
  • 0.0.138                                ...           8 months ago
  • 0.0.137                                ...           a year ago
  • 0.0.136                                ...           a year ago
  • 0.0.135                                ...           a year ago
  • 0.0.134                                ...           a year ago
  • 0.0.133                                ...           a year ago
  • 0.0.132                                ...           a year ago
  • 0.0.131                                ...           a year ago
  • 0.0.130                                ...           a year ago
  • 0.0.129                                ...           a year ago
  • 0.0.128                                ...           a year ago
  • 0.0.127                                ...           a year ago
  • 0.0.126                                ...           a year ago
  • 0.0.125                                ...           a year ago
  • 0.0.124                                ...           2 years ago
  • 0.0.123                                ...           2 years ago
  • 0.0.122                                ...           2 years ago
  • 0.0.121                                ...           2 years ago
  • 0.0.120                                ...           2 years ago
  • 0.0.119                                ...           2 years ago
  • 0.0.118                                ...           2 years ago
  • 0.0.117                                ...           2 years ago
  • 0.0.116                                ...           2 years ago
  • 0.0.115                                ...           2 years ago
  • 0.0.114                                ...           2 years ago
  • 0.0.113                                ...           2 years ago
  • 0.0.112                                ...           2 years ago
  • 0.0.111                                ...           2 years ago
  • 0.0.110                                ...           2 years ago
  • 0.0.109                                ...           2 years ago
  • 0.0.108                                ...           2 years ago
  • 0.0.107                                ...           2 years ago
  • 0.0.106                                ...           2 years ago
  • 0.0.105                                ...           2 years ago
  • 0.0.104                                ...           2 years ago
  • 0.0.103                                ...           2 years ago
  • 0.0.102                                ...           2 years ago
  • 0.0.101                                ...           2 years ago
  • 0.0.100                                ...           2 years ago
  • 0.0.99                                ...           3 years ago
  • 0.0.98                                ...           3 years ago
  • 0.0.97                                ...           3 years ago
  • 0.0.96                                ...           3 years ago
  • 0.0.95                                ...           3 years ago
  • 0.0.94                                ...           3 years ago
  • 0.0.93                                ...           3 years ago
  • 0.0.92                                ...           3 years ago
  • 0.0.91                                ...           3 years ago
  • 0.0.90                                ...           3 years ago
  • 0.0.89                                ...           3 years ago
  • 0.0.88                                ...           3 years ago
  • 0.0.87                                ...           3 years ago
  • 0.0.86                                ...           3 years ago
  • 0.0.85                                ...           3 years ago
  • 0.0.84                                ...           3 years ago
  • 0.0.83                                ...           3 years ago
  • 0.0.82                                ...           4 years ago
  • 0.0.81                                ...           4 years ago
  • 0.0.80                                ...           4 years ago
  • 0.0.79                                ...           4 years ago
  • 0.0.78                                ...           4 years ago
  • 0.0.77                                ...           4 years ago
  • 0.0.76                                ...           4 years ago
  • 0.0.75                                ...           4 years ago
  • 0.0.73                                ...           4 years ago
  • 0.0.72                                ...           4 years ago
  • 0.0.71                                ...           4 years ago
  • 0.0.70                                ...           4 years ago
  • 0.0.69                                ...           4 years ago
  • 0.0.68                                ...           4 years ago
  • 0.0.67                                ...           4 years ago
  • 0.0.66                                ...           4 years ago
  • 0.0.65                                ...           4 years ago
  • 0.0.64                                ...           4 years ago
  • 0.0.63                                ...           4 years ago
  • 0.0.62                                ...           4 years ago
  • 0.0.61                                ...           4 years ago
  • 0.0.60                                ...           4 years ago
  • 0.0.59                                ...           4 years ago
  • 0.0.58                                ...           4 years ago
  • 0.0.57                                ...           4 years ago
  • 0.0.56                                ...           4 years ago
  • 0.0.55                                ...           4 years ago
  • 0.0.53                                ...           4 years ago
  • 0.0.52                                ...           4 years ago
  • 0.0.51                                ...           4 years ago
  • 0.0.50                                ...           4 years ago
  • 0.0.49                                ...           4 years ago
  • 0.0.48                                ...           4 years ago
  • 0.0.47                                ...           4 years ago
  • 0.0.46                                ...           4 years ago
  • 0.0.45                                ...           4 years ago
  • 0.0.44                                ...           4 years ago
  • 0.0.43                                ...           4 years ago
  • 0.0.42                                ...           4 years ago
  • 0.0.41                                ...           4 years ago
  • 0.0.40                                ...           4 years ago
  • 0.0.39                                ...           4 years ago
  • 0.0.38                                ...           4 years ago
  • 0.0.37                                ...           4 years ago
  • 0.0.36                                ...           4 years ago
  • 0.0.35                                ...           4 years ago
  • 0.0.34                                ...           4 years ago
  • 0.0.33                                ...           4 years ago
  • 0.0.32                                ...           5 years ago
  • 0.0.31                                ...           5 years ago
  • 0.0.30                                ...           5 years ago
  • 0.0.29                                ...           5 years ago
  • 0.0.28                                ...           5 years ago
  • 0.0.27                                ...           5 years ago
  • 0.0.26                                ...           5 years ago
  • 0.0.25                                ...           5 years ago
  • 0.0.24                                ...           5 years ago
  • 0.0.23                                ...           5 years ago
  • 0.0.22                                ...           5 years ago
  • 0.0.21                                ...           5 years ago
  • 0.0.19                                ...           5 years ago
  • 0.0.18                                ...           5 years ago
  • 0.0.17                                ...           5 years ago
  • 0.0.16                                ...           5 years ago
  • 0.0.15                                ...           5 years ago
  • 0.0.14                                ...           5 years ago
  • 0.0.13                                ...           5 years ago
  • 0.0.12                                ...           5 years ago
  • 0.0.11                                ...           5 years ago
  • 0.0.10                                ...           5 years ago
  • 0.0.9                                ...           5 years ago
  • 0.0.8                                ...           5 years ago
  • 0.0.7                                ...           5 years ago
  • 0.0.6                                ...           5 years ago
  • 0.0.5                                ...           5 years ago
  • 0.0.4                                ...           5 years ago
  • 0.0.3                                ...           5 years ago
  • 0.0.2                                ...           5 years ago
  • 0.0.1                                ...           5 years ago
  • 0.0.0                                ...           5 years ago
Maintainers (2)
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 21
Dependencies (8)
Dev Dependencies (12)

Copyright 2014 - 2016 © taobao.org |