Mongoose Queries Model.deleteOne() API
Mongoose module is one of Node.js’s most potent external modules. To transfer the code and its representation from MongoDB to the Node.js server, Mongoose is a MongoDB ODM (Object Database Modelling) tool.
The deleteOne() function is used to delete the first document which matches the condition.
Syntax:
deleteOne(conditions, options)
Parameters:
- conditions: The filter conditions.
- options: The options object.
Returns: An object with the count of deleted documents.
Installation of mongoose module:
Step 1: You can install this package by using this command.
npm install mongoose
Step 2: After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm version mongoose
Step 3: After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Following is the dataset, I am using in the following examples.
Example 1: In this example, we are trying to delete a document with _id=11. As there is no such document in the data we are using, hence no document will be deleted.
Javascript
const Person = require( "../mongoose/model/person" );
const mongoose = require( "mongoose" );
let mongoDB = mongoose.connect
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
let db = mongoose.connection;
db.on( "error" , console.error.bind(console,
"MongoDB Connection Error" ));
(async () => {
const res = await Person.deleteOne(
{ _id: 11 },
);
console.log(`Number of Deleted Documents: ${res.deletedCount}`);
})();
|
Output:
Example 2: In this example, we are trying to delete a document with last_name=Bourgeois. As there is a document that matches the condition, it will be deleted.
Javascript
const Person = require( "../mongoose/model/person" );
const mongoose = require( "mongoose" );
let mongoDB = mongoose.connect
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
let db = mongoose.connection;
db.on( "error" , console.error.bind(console, "
MongoDB Connection Error" ));
(async () => {
const res = await Person.deleteOne
({ last_name: "Bourgeois" });
console.log(`Number of Deleted Documents:
${res.deletedCount}`);
})();
|
Output:
Reference: https://mongoosejs.com/docs/api/model.html#model_Model-deleteOne
Last Updated :
07 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...