Created
November 22, 2017 07:24
-
-
Save salmanx/9654258db9e791d35c89fb0652ace19a to your computer and use it in GitHub Desktop.
seeding data in mongo db client
This file contains hidden or 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
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