Created
September 3, 2016 20:49
-
-
Save mleanos/81fa1ca3730fc266df95b2946f0f0aec to your computer and use it in GitHub Desktop.
Script for seeding many Articles in the MEANJS framework. Locally, this script resides in a sub-folder of the /scripts folder that I've added to my global .gitignore. The paths of the dependencies may need to be updated for your purposes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var mongoose = require('mongoose'), | |
chalk = require('chalk'), | |
config = require('../../config/config'), | |
mg = require('../../config/lib/mongoose'); | |
mg.loadModels(); | |
var seedCount = 100000; | |
var seededArticles = [], | |
errors = [], | |
processedCount = 0; | |
mg.connect(function (db) { | |
var Article = mongoose.model('Article'); | |
for (var i = 0; i < seedCount; i++) { | |
//console.log('adding #' + (i + 1)); | |
//console.log('article (before): ', article); | |
try { | |
var createdAt = new Date(Date.now()); | |
//console.log('createdAt: ', createdAt); | |
var article = new Article({ | |
created: createdAt, | |
title: 'Seeded Article - ' + createdAt.toLocaleDateString(), | |
content: 'This is the #' + (i + 1) + ' article that was added with the script', | |
user: '5626bdec39b6617808bdf661' | |
}); | |
article.save(saveCallback(article)); | |
} catch (err) { | |
errors.push(err); | |
reportUnhandledError(err, seededArticles, errors); | |
} | |
} | |
}); | |
function saveCallback(article) { | |
return function (err) { | |
processedCount++; | |
if (err) { | |
errors.push(err); | |
} else { | |
seededArticles.push(article); | |
} | |
if (processedCount === seedCount) { | |
reportAndExit(seededArticles, errors); | |
} | |
} | |
} | |
function reportUnhandledError(err, articles, errors) { | |
console.log(); | |
console.log('An unhandled error occured'); | |
console.log(err); | |
console.log(); | |
reportAndExit(articles, errors); | |
} | |
function reportAndExit(articles, errors) { | |
console.log('articles added: ', articles.length); | |
console.log('error count: ', errors.length); | |
process.exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment