2012-10-11 65 views
3

我想用我的一些測試數據填充我的mongo。nodejs mongo,生成測試數據

我已經定義了貓鼬模型,並且如果可以使用預先定義的模型實用地創建mongo文檔,我就會徘徊。

例如,模型項目

var Schema = mongoose.Schema; 

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

回答

2

當然,做一個單一目的節點的應用程序。創建一個不使用快速或任何Web框架的新應用程序,而只需創建模型定義並連接到數據庫。

你當然需要測試數據,你可以只使用一個隨機單詞生成一個數據源,像這樣的: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; 
} 

然後,你需要填充如數據庫這個:

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

然後只運行該節點的應用程序。