Mongoose Document Model.prototype.remove()函数

Mongoose Document Model.prototype.remove()函数

Mongoose API的 Model.remove() 方法用于从MongoDB数据库中删除文档。我们可以在任何模型对象上访问 remove() 方法,并且在方法成功执行后,该特定文档将从数据库中删除。

语法:

Model.remove() 
JavaScript

参数: Model.remove()方法接受两个参数:

  • options: 它是一个带有各种属性的对象。
  • callback: 这是一个回调函数,一旦执行完成就会运行。

返回值: Model.remove()函数返回一个Promise。

设置Node.js应用程序:

步骤1: 使用以下命令创建一个Node.js应用程序:

npm init
JavaScript

步骤2: 在创建了NodeJS应用程序之后,使用以下命令安装所需的模块:

npm install mongoose
JavaScript

项目结构:

项目的结构将会如下所示:

Mongoose Document Model.prototype.remove()函数

数据库结构: 数据库结构将会如下所示,集合中包含以下文档。

Mongoose Document Model.prototype.remove()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了一个模型,有两个列或字段“name”和“age”。最后,我们使用其ObjectId从数据库中获取到了一个文档对象“User1”,然后使用 remove() 从数据库中移除该文档。在GUI输出中,我们可以看到“_id”为“63203694182cd3c22ea480ff”的文档已被移除。

  • app.js: 将以下代码写入app.js文件中:
// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const userSchema = new mongoose.Schema({ 
    name: String, 
    age: Number, 
}); 
  
// Defining userSchema model 
const User = mongoose.model("User", userSchema); 
  
User.findById("63203694182cd3c22ea480ff").then(doc => { 
    doc.remove(); 
})
JavaScript

运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:

node app.js
JavaScript

使用Robo3T GUI工具GUI表示的数据库:

Mongoose Document Model.prototype.remove()函数

示例2: 在此示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了model,它有两个列或字段“name”和“age”。最后,我们使用其ObjectId从数据库中获取一个文档对象即“User2”,并使用remove()方法删除该文档。删除文档后,我们再次获取相同的文档,您可以看到我们得到了“null”值。在GUI输出中,我们可以看到具有“_id”为“63204ad5182cd3c22ea486ae”的文档已被删除。

  • app.js: 在app.js文件中编写以下代码:
// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const userSchema = new mongoose.Schema({ 
    name: String, 
    age: Number, 
}); 
  
// Defining userSchema model 
const User = mongoose.model("User", userSchema); 
  
const removeDocument = async () => { 
    const doc = await User.findById("63204ad5182cd3c22ea486ae") 
    doc.remove(); 
    const doc1 = await User.findById("63204ad5182cd3c22ea486ae") 
    console.log(doc1) 
} 
  
removeDocument();
JavaScript

运行程序的步骤

要运行应用程序,请在项目的根目录下执行以下命令:

node app.js
JavaScript

输出:

null
JavaScript

使用Robo3T GUI工具的数据库的GUI表示:

Mongoose Document Model.prototype.remove()函数

参考: https://mongoosejs.com/docs/api/model.html#model_Model-remove

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册