What is remove() function in Mongoose?

remove() is a Mongoose function that removes a given path or paths from a document. It removes the path based on the passed argument.

A path is a field in a document present in a database or collection.

Syntax

Schema.remove(path)

Parameter

path: this is the path you want to be removed.

Return value

A schema instance is returned.

Code

// import mongoose
const mongoose = require("mongoose");
// creating a product Schema with mongoose
let Product = mongoose.model("Item", new mongoose.Schema({
name: String,
category: Number,
price: Number,
tag: String
})
)
// check if product Educative.io
// exists with the exists() method
let product = await Product.remove("category");
console.log(product.path("category")) // Undefined

Explanation

In the example below, we create a Product Schema and remove the category path with the remove() function. Then we log out the removed path to see if it still exists.

After the successful removal of the “category” path, Undefined is returned when you try and find the path again.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources