Custom fixtures generator for nodejs / mongodb in 30 seconds

I recently needed to generate random users for a NodeJS project using mongo. I remember the time I used the powerful Alice fixture generator for my Symfony2 projects.

Actually, I didn’t find anything as complete as Alice but I found two very interesting npm modules.

The first one is faker. It generates random data such as names, addresses, etc.

The second one is pow-mongodb-fixtures. It allows you to record custom data in mongo in a snap.

We first need to install these modules. I choose to save them in my dev dependency but it’s totally up to you:

npm install faker --save-dev
npm install pow-mongodb-fixtures --save-dev

Then I created a coffee script to be called when I want to load random fixtures. It resets the content of the ‘myCollectionName’ collection of the ‘myDbName’ database. Then it enters objects that have two attributes: ‘lastName’ and ‘firstName’.

fixtures = require('pow-mongodb-fixtures').connect 'myDbName'
faker = require 'faker'

# Generate random data
users = []
for i in [1..10]

# Record these data in the 'myCollectionName' collection
fixtures.clearAndLoad {myCollectionName: users}, (err) ->
  throw err if err
  console.log '10 users have been recorded!'
  fixtures.close ->

I can now load fixtures with


This exemple is very simple but you can generate anything you want with faker : addresses, phone numbers, dates. Check the faker github repository for more infos.

You liked this article? You'd probably be a good match for our ever-growing tech team at Theodo.

Join Us