user1736526 user1736526 -5 years ago 193
Node.js Question

nodejs mongo, generate test data

I would like to populate my mongo with some test data.

I have defined mongoose models and I was wandering if it was possible to pragmatically create mongo documents using pre defined models.

For example, model Items

var Schema = mongoose.Schema;

var Items = new Schema({
title: { type: String, required: true },
desc: { type: String}

Answer Source

Sure, do it in a single-purpose node app. Create a new app that doesn't use express or whatever web framework, but instead just has your model definition and a connection to your database.

You'll need a data source of course for the test data, which you could just use a random word generator, like this one:

function createRandomWord(length) {
    var consonants = 'bcdfghjklmnpqrstvwxyz',
        vowels = 'aeiou',
        rand = function(limit) {
            return Math.floor(Math.random()*limit);
        i, word='', length = parseInt(length,10),
        consonants = consonants.split(''),
        vowels = vowels.split('');
    for (i=0;i<length/2;i++) {
        var randConsonant = consonants[rand(consonants.length)],
            randVowel = vowels[rand(vowels.length)];
        word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
        word += i*2<length-1 ? randVowel : '';
    return word;

Then you'd need to populate the database like this:

var numTestDocs = 100; // or however many you want
for(var i = 0; i < numTestDocs; i++) {
   var someLength = 12; // Alternatively, you could use a random number generator
   var randomWord = createRandomWord(someLength);
   var item = new Item ({
      title : randomWord ,
      desc  : randomWord + ' is just a test'
   });, doc) {
      // do error handling if you want to
      console.log('Test Record Saved with id: ' + doc._id);

Then just run that node app.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download