Skip to content

Instantly share code, notes, and snippets.

@salmanx
Created November 22, 2017 07:24
Show Gist options
  • Save salmanx/9654258db9e791d35c89fb0652ace19a to your computer and use it in GitHub Desktop.
Save salmanx/9654258db9e791d35c89fb0652ace19a to your computer and use it in GitHub Desktop.
seeding data in mongo db client
require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;
const bcrypt = require('bcrypt');
const users = require('./users');
function seedCollection(collectionName, initialRecords){
MongoClient.connect(process.env.DB_CONN, (err, db) => {
console.log("connected to mongo db");
const collection = db.collection(collectionName);
collection.remove();
initialRecords.forEach(item => {
if(item.password){
item.password = bcrypt.hashSync(item.password, 10);
}
});
collection.insertMany(initialRecords, (err, records) => {
console.log(`${records.insertedCount} records inserted.`);
console.log('closing connection');
db.close();
console.log('done');
});
});
}
seedCollection('users', users); // 'users' will be the name of collection in mlab
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment