lobo-mongodb-fixtures
This is a forked version of pow-mongodb-fixtures, that merges all other forks into this one, trying to keep it up to date.
Simple fixture loader for MongoDB on NodeJS. Makes managing relationships between documents easier.
Fixtures can be in one file, or divided up into separate files for organisation (e.g. one file per model)
The fixture files must export objects which are keyed by the MongoDB collection name, each containing the data for documents within that.
Installation
npm install lobo-mongodb-fixtures
Examples
With the file below, 3 documents will be inserted into the 'users' collection and 2 into the 'businesses' collection:
//fixtures.jsexportsusers = name: 'Gob' name: 'Buster' name: 'Steve Holt' ; exportsbusinesses = name: 'The Banana Stand' name: 'Bluth Homes' ;
You can also load fixtures as an object where each document is keyed, in case you want to reference another document. This example uses the included createObjectId
helper:
//users.jsvar id = createObjectId; var users = exportsusers = user1: _id: name: 'Michael' user2: _id: name: 'George Michael' father: usersuser1_id user3: _id: name: 'Tobias'
CLI usage
A CLI program is included for quickly loading fixture files. To use it install the module globally:
npm install lobo-mongodb-fixtures -g
Then use the program to install a file or directory:
mongofixtures <dbname> <fixture file>
mongofixtures appdb fixtures/users.js
API
connect(dbname, options)
Returns a new Loader instance, configured to interact with a certain database.
Options:
- host (Default: localhost)
- port (Default: 27017)
- user
- pass
- safe (Default: false)
Usage:
var fixtures = ; var fixtures2 = ;
load(data, callback)
Adds documents to the relevant collection. If the collection doesn't exist it will be created first.
var fixtures = ; //Objectsfixtures; //Filesfixtures; //Directories (loads all files in the directory)fixtures;
clear(callback)
Clears existing data.
fixturesclear { //Drops the database}; fixturesclear'foo' { //Clears the 'foo' collection}; fixturesclear'foo' 'bar' { //Clears the 'foo' and 'bar' collections};
clearAllAndLoad(data, callback)
Drops the database (clear all collections) and loads data.
clearAndLoad(data, callback)
Clears the collections that have documents in the data
that is passed in, and then loads data.
var data = users: ... ; fixtures;
addModifier(callback)
Adds a modifier (function) which gets called for each document that is to be inserted. The signature of this function should be:
collectionName document callback
- collectionName - name of collection
- document - the document which is to be inserted
- callback - function with signature (err, modifiedDocument). This should be called with the modified document.
Modifiers are chained in the order in which they're added. For example:
var data = users: ... ; // this modifier will get called firstfixtures; // this modifier will get called second with the result from the first modifier callfixtures; fixtures;