Over a million developers have joined DZone.

Creating Test Data in MongoDB Using Node.js

Rather than create test documents ordered by date by hand, using the Node.js driver for MongoDB makes this pretty easy with only a few lines of code.

· Database Zone

Sign up for the Couchbase Community Newsletter to stay ahead of the curve on the latest NoSQL news, events, and webinars. Brought to you in partnership with Coucbase.

I need to create a fairly large number of test documents in my MongoDB to test some functionality that will be retrieving pages of data, ordered by date.

Rather than doing this by hand, using the Node.js driver for MongoDB makes this pretty easy with only a few lines of code. This is a starting point, in my case I need to add some additional logic to increment a date value and create some other random values on each doc, but this is a rough outline of an approach:

Assuming Node.js already installed, install the MongoDB Node.js driver with:

npm install mongodb

Then the code to install multiple docs in one shot looks something like this:

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');

var ObjectId = require('mongodb').ObjectID;

MongoClient.connect('mongodb://localhost:27017/databasename', function(err, db) {
  test.equal(err, null);

  var col = db.collection('collectioname');
  var docs = [];

  //update this for how many docs to insert

  for(i=0; i<10; i++){
    docs[i] = {a:i}; // create doc here using json
  }

  col.insertMany(docs, function(err, r) {
    test.equal(err, null);
    console.log(r.insertedCount);
    db.close();
  });
});

Run the script with:

node scriptname.js

Additional info in the MongoDB Getting Started Guide for node.js.

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:
nosql ,mongodb ,node.js ,database

Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}