3

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}
});
4

2 回答 2

2

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: http://james.padolsey.com/javascript/random-word-generator/

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'
   });
   item.save(function(err, doc) {
      // do error handling if you want to
      console.log('Test Record Saved with id: ' + doc._id);
   });
}

Then just run that node app.

于 2012-10-11T14:07:18.490 回答
1

There are many ways to do this using different mongoose modules. Go and check mongoose fakery.

https://www.npmjs.org/package/mongoose-fakery

于 2014-04-17T22:03:23.440 回答