Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.