Skip to content

Instantly share code, notes, and snippets.

@catwhocode
Created December 30, 2021 09:47
Show Gist options
  • Save catwhocode/81df246a42cb1b5767106838285446d2 to your computer and use it in GitHub Desktop.
Save catwhocode/81df246a42cb1b5767106838285446d2 to your computer and use it in GitHub Desktop.
Connect to MongoDB and insert many data
const mongodb = require('mongodb')
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017/mydb'
MongoClient.connect(url, function(err, db){
if (err) throw err;
console.log('Connected to mydb')
const dbo = db.db('mydb')
const users = [
{username: 'eric', name: 'Eric Clapton', email: '[email protected]'},
{username: 'jovi', name: 'Jon Bon Jovi', email: '[email protected]'},
{username: 'satriani', name: 'Joe Satriani', email: '[email protected]'},
]
dbo.collection('users').insertMany(users, function(err, result){
if (err) throw err;
console.log(users.length + ' users inserted')
db.close()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment