Skip to content

Instantly share code, notes, and snippets.

@kerminz
Created May 19, 2019 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerminz/93d4468702c7127cc33cc7f7c5e5391d to your computer and use it in GitHub Desktop.
Save kerminz/93d4468702c7127cc33cc7f7c5e5391d to your computer and use it in GitHub Desktop.
CRUD – MongoDB + NodeJS
// CRUD create read update delete
const { MongoClient, ObjectID } = require('mongodb')
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'databaseName'
MongoClient.connect(connectionURL, { useNewUrlParser: true }, (error, client) => {
if (error) {
return console.log('Unable to connect to database!')
}
const db = client.db(databaseName)
// CREATE
db.collection('users').insertOne({
name: 'Peter',
age: 26
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
db.collection('users').insertMany([
{
name: 'Daniel',
age: 29
}, {
name: 'Günther',
age: 50
}
]).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
// READ
db.collection('users').findOne({
_id: new ObjectID('5ce0881d3b614fa9dc57835b'),
age: 32
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
db.collection('users').find({age: 18}).toArray().then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
// UPDATE
db.collection('users').updateOne({
name: 'Daniel'
}, {
$set: {
age: 30
}
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
db.collection('users').updateMany( {
age: 30
}, {
$set: {
name: 'Finn',
age: 18
}
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
// DELETE
db.collection('tasks').deleteOne({
description: 'Finish coding the giphy app'
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
db.collection('users').deleteMany({
age: 50
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment