Setup and tear down test fixtures with MongoDB.
npm install node-mongodb-fixtures
For CLI use, it can be useful to install globally:
npm install node-mongodb-fixtures -g
The following example will load the example fixtures into a MongoDB database
- A valid MongoDB connection string
- node-mongodb-fixtures (This example assumes it is installed globally)
-
clone this repo to get the sample fixtures i.e.
./examples/fixtures
-
Execute
❯ mongodb-fixtures load -u mongodb://localhost:27017/mydb --path ./examples/fixtures
const Fixtures = require('node-mongodb-fixtures');
const fixtures = new Fixtures();
fixtures.connect('mongodb://localhost:27017/mydb').load() // load
See detailed programmatic usage below
❯ mongodb-fixtures load -u mongodb://localhost:27017/mydb'
- Choose a directory for your fixtures e.g.
./fixtures
- Create a number of JSON files.
- Each JSON filename defines MongoDB collection.
- Each file must contain a JSON Array of JSON objects. e.g.
[
{ "name": "Paul", "age": 36 },
{ "name": "Phoebe", "age": 26 }
]
- Each JSON object is loaded as a document in the collection.
fixtures/
|-- people.json
|-- places.json
use the default fixtures directory,./fixtures
const Fixtures = require('node-mongodb-fixtures');
const fixtures = new Fixtures();
or specifiy the fixtures directory
const Fixtures = require('node-mongodb-fixtures');
const fixtures = new Fixtures({
dir: 'examples/fixtures'
});
Use the standard MongoDB URI connection scheme
fixtures.connect('mongodb://localhost:27017/mydb')
connect(uri, options, dbName)
arg | type | description |
---|---|---|
uri |
string (required) | MongoDB connection string |
options |
object (optional) | MongoDB connection options |
dbName |
string (optional) | identifies a database to switch to. Useful when the db in the connection string differs from the db you want to connect to |
See: ./examples/ex1.js
fixtures.load()
fixtures.unload()
fixtures.disconnect()
The following example does the following:
- connects to mongo
- then unloads all fixtures
- then load all fixtures
- then disconnects
const Fixtures = require('node-mongodb-fixtures');
const uri = 'mongodb://localhost/mydb'
const options = null;
const fixtures = new Fixtures({
dir: 'examples/fixtures'
});
fixtures
.connect('mongodb://localhost:27017/mydb')
.unload()
.then(() => fixtures.load())
.catch(e => console.error(e))
.finally(() => fixtures.disconnect());
❯ mongodb-fixtures
Usage: mongodb-fixtures [options] [command]
Options:
-V, --version output the version number
-u --url <url> mongo connection string
-s --ssl use SSL
-d --db_name <name> database name
-n --ssl_novlidate use SSL with no verification
-c --ssl_ca <base64> path to cert
-p --path <path> resource path. Default ./fixtures
-b --verbose verbose logs
-h, --help output usage information
Commands:
load
unload
rebuild