Advertisement
Guest User

Untitled

a guest
Apr 12th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. const fs = require('fs')
  2. const mongoClient = require('mongodb').MongoClient
  3.  
  4. const databaseInfo = {
  5. host: 'host',
  6. port: 'port',
  7. user: 'username',
  8. pass: 'password',
  9. db: 'database',
  10. collection: 'collection',
  11. get url () {
  12. return `mongodb://${this.user}:${this.pass}@${this.host}:${this.port}/${this.db}`
  13. }
  14. }
  15.  
  16. const MONGO_URL = databaseInfo.url
  17. const COLLECTION = databaseInfo.collection
  18.  
  19. const insertDocuments = (db, data, callback) => {
  20. const collection = db.collection(COLLECTION)
  21.  
  22. collection.insertMany(data, (err, result) => {
  23. if (err) {
  24. throw err
  25. }
  26.  
  27. console.log('THE DATA HAS BEEN SAVED.')
  28. callback(result)
  29. })
  30. }
  31.  
  32. mongoClient.connect(MONGO_URL, (err, db) => {
  33. if (err) {
  34. throw err
  35. }
  36.  
  37. fs.readFile('./sample.json', 'utf8', (err, data) => {
  38. if (err) {
  39. throw err
  40. }
  41.  
  42. insertDocuments(db, JSON.parse(data), () => {
  43. db.close()
  44. })
  45. })
  46. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement