Skip to content

Instantly share code, notes, and snippets.

@viniciusCamargo
Created April 12, 2017 20:20
Show Gist options
  • Save viniciusCamargo/412be7f960fec9b3916128ca8d9026c3 to your computer and use it in GitHub Desktop.
Save viniciusCamargo/412be7f960fec9b3916128ca8d9026c3 to your computer and use it in GitHub Desktop.
Save an array of objects to MongoDB
const fs = require('fs')
const mongoClient = require('mongodb').MongoClient
const databaseInfo = {
host: 'host',
port: 'port',
user: 'username',
pass: 'password',
db: 'database',
collection: 'collection',
get url () {
return `mongodb://${this.user}:${this.pass}@${this.host}:${this.port}/${this.db}`
}
}
const MONGO_URL = databaseInfo.url
const COLLECTION = databaseInfo.collection
const insertDocuments = (db, data, callback) => {
const collection = db.collection(COLLECTION)
collection.insertMany(data, (err, result) => {
if (err) {
throw err
}
console.log('THE DATA HAS BEEN SAVED.')
callback(result)
})
}
mongoClient.connect(MONGO_URL, (err, db) => {
if (err) {
throw err
}
fs.readFile('./sample.json', 'utf8', (err, data) => {
if (err) {
throw err
}
insertDocuments(db, JSON.parse(data), () => {
db.close()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment