Created
April 12, 2017 20:20
-
-
Save viniciusCamargo/412be7f960fec9b3916128ca8d9026c3 to your computer and use it in GitHub Desktop.
Save an array of objects to MongoDB
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
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