In this Chapter , we will learn about deleting the first occurance of the data searched using a search query parameter in the deleteOne method of mongoDb database.
Step - 1 : Including Packages
We will start by
requiring the package.
We are using the following package in our application :
var mongo = require('mongodb');
Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.
var new_db = "mongodb://localhost:27017/demo_db"
Step - 3 : delete
deleteOne() is the inbuilt method of mongodb which is used to delete
the first occurance of the data provided in the search query.
Syntax
The syntax for deleteOne is :
db.collection("NAME_OF_THE_COLLECTION").deleteOne(SEARCH_CONDITION ,(CALLBACK_FUNCTION) => {});
//deleteOne-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to the database using nodejs
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//query stores the search condition
var query = { age : "above 22" };
//Accessing a COLLECTION IN MONGODB USING NODE.JS
db.collection("details").deleteOne(query , (err , collection) => {
if(err) throw err;
console.log(collection.result.n + " Record(s) deleted successfully");
console.log(collection);
db.close();
});
});
D:\nj-learn-mongo>node deleteOne-mongodb-nodejs.js
D:\nj-learn-mongo>node deleteOne-mongodb-nodejs.js
1 Record(s) deleted successfully
{
result:
{
ok: 1,
n: 1
},
connection: null,
message: undefined,
deletedCount: 1
}