In this lesson I am going to explain you how to get started with Express.js and MongoDB
First we will see how we connect to the MongoDB and then we will study basic database operations like Create,Read,Update and Delete (CRUD)
We will see how to create new collection in “Test” database
const express = require('express') const app = express() const port = 3000 const MongoClient=require("mongodb") var url = "mongodb://localhost:27017/test" app.get('/', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!"); db.close(); }); response.send('Hello from Express!') }) app.listen(port, function () { console.log('Example app listening on port 3000!') })
Code explanation
MongoClient.connect
is used with connection url to the database. This will create new database if it is not exists and make a connection to itWe will see how to create “products” collection in MongoDB
const MongoClient=require("mongodb") const express = require('express') const app = express() const port = 3000 let url = "mongodb://localhost:27017/test" app.get('/', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; db.createCollection("products",function(err, res) { if (err) throw err; console.log("Collection created!"); db.close(); }) }); response.send('Hello from Express!') }) app.listen(port, function () { console.log('Example app listening on port 3000!') })
Code explanation
db.createCollection
is the method we used to create new collection. You have the callback function like the above exampleNow we will see how to insert document to collection (in MongoDB we call it document but in Mysql we call it record)
app.get('/insert', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; var product={product_id:2, product_name:'Coca Cola'} db.collection("products").insertOne(product, function(err, res) { if (err) throw err; db.close(); }); }) response.send('1 document inserted') })
Code explanation
var product={product_id:2, product_name:'Coca Cola'}
We create the objects which we want to insertdb.collection("products").insertOne
to insert document to collectionNow you can try to add several documents to the “product” collection
In MongoDB you have find
and findOne
method to find document in collection. We will see how we can use those methods
app.get('/find', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("products").find({}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }) response.send('Document Found') })
You can see the following output in terminal
[ { _id: 59982cca0c944faa65f0b8d9, product_id: 1, product_name: 'Coca Cola' }, { _id: 5998598cf4eae6aad85b81db, product_id: 3, product_name: 'Sprite' } ]
Code explanation
db.collection("products").find
to find all documents in the collection.find()
is empty object {}
find()
is equal to the SELECT *
in MYSQLfindOne
method will return only the first resultOther important thing with find()
is the query object.
You can create the query object according to your criteria
app.get('/find', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; var query={product_name:'Coca Cola'} db.collection("products").find(query).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); }) response.send('Document Found') })
Terminal Output
[ { _id: 59982cca0c944faa65f0b8d9, product_id: 1, product_name: 'Coca Cola' } ]
Code explanation
var query={product_name:'Coca Cola'}
.var query = { product_name: /^C/ }
. This will get you the products which product_name is started with letter CNow we are going to update the document. I want to update product_name:”Sprite” with product_name:”Fanta”
app.get('/update', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; var query={product_name:'Sprite'} var newObject={product_id:3,product_name:'Fanta'} db.collection("products").updateOne(query,newObject,function(err, res) { if (err) throw err; db.close(); }); }) response.send('Document Updated') })
Code explanation
updateOne
method will update all the fields of the document$set
operator var newObject = {$set: { product_name: "Fanta" } }
; So this will not update other fields as blankYou can use deleteOne()
method in node.js to delete document from MongoDB collection
app.get('/delete', (request, response) => { MongoClient.connect(url, function(err, db) { if (err) throw err; var query={product_id:3} db.collection("products").deleteOne(query,function(err, res) { if (err) throw err; db.close(); }); }) response.send('Document Deleted') })
Code explanation
Line 5: You can define the query object defining which element to delete
Line 7: Passing the query
object parameter to the deleteOne()
You can use the deleteMany()
to delete multiple documents