Created
May 19, 2019 17:35
-
-
Save kerminz/93d4468702c7127cc33cc7f7c5e5391d to your computer and use it in GitHub Desktop.
CRUD – MongoDB + NodeJS
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
// 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