Mongoose Document Model.remove()函数

Mongoose Document Model.remove()函数

Mongoose API的Model.remove()方法用于一次性删除集合中的所有文档。它将在已定义和存在于数据库中的Collection模型上调用。

语法:

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.remove()函数

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

Mongoose Document Model.remove()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在customerSchema上定义了model,其中有三列或字段“name”,“orderCount”,和“superUser”。最后,我们在Customer model上使用 remove() 方法,该方法将删除Customer model中的所有文档。输出结果将得到一个带有两个属性的对象:- “acknowledged”表示一切顺利进行,“deletedCount”表示删除的文档数。

  • 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
}) 
  
// Defining customerSchema schema 
const customerSchema = new mongoose.Schema( 
    { name: String, orderCount: Number, superUser: Boolean} 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model('Customer', customerSchema); 
  
Customer.remove().then(result => { 
    console.log(result) 
})
JavaScript

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

node app.js
JavaScript

输出:

{ acknowledged: true, deletedCount: 3 }
JavaScript

使用Robo3T GUI工具对数据库进行图形化界面(GUI)表示:

Mongoose Document Model.remove()函数

示例2: 在这个示例中,我们定义了usersSchema和User模型。在User模型上,我们调用了 remove() 在最后,将所有记录从数据库中删除后,我们使用User模型上的find()方法搜索文档,在结果中我们得到了一个空的结果,显示User集合中没有记录。

  • 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 } 
) 
  
// Defining userSchema model 
const User = mongoose.model('User', userSchema); 
  
User.remove().then(result => { 
    console.log(result) 
}) 
  
User.find({_id: '630db5818577bafc2709d603'}). 
   then(result => { 
    console.log(result) 
})
JavaScript

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

node app.js
JavaScript

输出:

{ acknowledged: true, deletedCount: 2 }
[]
JavaScript

使用Robo3T GUI工具对数据库进行GUI表示:

Mongoose Document Model.remove()函数

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册