Open In App

How to Delete a Key from a MongoDB Document using Mongoose?

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. When working with MongoDB using Mongoose, a MongoDB object modeling tool designed to work in an asynchronous environment and developers encounter scenarios where they need to delete a key from a document.

In this article, We will learn about the process of deleting a key from a MongoDB document using Mongoose by understanding the various methods along with the examples and so on.



How to Delete a key from a MongoDB document using Mongoose?

When working with MongoDB and Mongoose, developers often need to perform tasks such as updating documents, deleting keys, and executing complex queries. Below methods help us to understand How to Delete a key from a MongoDB document using Mongoose are as follow:

  1. Using the updateOne() method
  2. Using the findOneAndUpdate() method

Steps to Create Database Connection and Mongoose Schema

Step 1: Install Necessary Dependencies

npm install mongoose

Step 2: Create the MongoDB connection

const mongoose = require("mongoose");

mongoose
.connect("mongodb://localhost:27017/gfg")
.then(() => {
console.log("Connected to MongoDB database successfully!");
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err);
});

Step 3: Create a Mongoose Schema

const mongoose = require("mongoose");

const courseSchema = new mongoose.Schema({
Title: {
type: String,
},
Fees: {
type: Number,
},
Instructor: {
type: String,
},
date: Date,
});

const Course = mongoose.model("Course", courseSchema);

module.exports = Course;

Step 4: Query Delete a key from a MongoDB document using Mongoose Using Below Approaches

1. Using updateOne() Method with $unset Operator

Syntax:



Model.updateOne(
<filter>,
<update>,
[options],
[callback]
)

Explanation:

Let’s set up an Environment

To understand How to Delete a key from a MongoDB document using Mongoose we need a collection and some documents on which we will perform various queries. Here we will consider a collection called courses which contains information like course name, Instructore name, fees and date of the courses in various documents.

Example 1: Removing the Fees key from the document

Add the code into the queryData.js file and run using node queryData.js command

Query:

const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");

async function deleteKeyFromDocument() {
try {
await Course.updateOne({}, { $unset: { Fees: 1 } });
console.log("Key deleted successfully from document");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}

deleteKeyFromDocument();

Output:

fees-1

Explanation:

Example 2: Removing the Instrctutor key from the document

Query:

const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");

async function deleteKeyFromDocument() {
try {
await Course.updateOne({}, { $unset: { Instructor: 1 } });
console.log("Key deleted successfully from document");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}

deleteKeyFromDocument();

Output:

instructor

Explanation:

2. Using findOneAndUpdate() Method with $unset Operator

In MongoDB, findOneAndUpdate() is a method that combines the functionality of findOne() and update() in a single atomic operation. This method used to find a single document that matches the specified filter criteria, update it, and return the updated document.

Syntax:

    Model.findOneAndUpdate(filter, update, options, callback)

Explanation:

Example 1: Removing the Fees key from the document

Query:

const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");

async function deleteKeyFromDocument() {
try {
await Course.findOneAndUpdate(
{},

{ $unset: { Fees: 1 } },

{ new: true }
);

console.log("Key deleted successfully from the document:");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}

deleteKeyFromDocument();

Output:

fees

Explanation:

Example 2: Removing the Instructor Key From the Document

Query:

const mongoose = require("mongoose");
const Course = require("./model");
const db = require("./dbConnect");

async function deleteKeyFromDocument() {
try {
await Course.findOneAndUpdate(
{},

{ $unset: { Instructor: 1 } },

{ new: true }
);

console.log("Key deleted successfully from the document:");
const courses = await Course.find({});
console.log("Courses after deletion:");
console.log(courses);
} catch (error) {
console.error("Error deleting key:", error);
} finally {
mongoose.disconnect();
}
}

deleteKeyFromDocument();

Output:

instructor

Explanation:

Conclusion

Overall, the Deleting a key from a MongoDB document using Mongoose is a straightforward process that involves using the findOneAndUpdate() method with the $unset operator. This approach allows you to modify MongoDB documents efficiently and is particularly useful when you need to remove unnecessary or sensitive data from your documents.


Article Tags :