Mongoose Schema Connection.prototype.close()函数

Mongoose Schema Connection.prototype.close()函数

Mongoose模式API Connection.prototype.close() 方法 用于Connection对象。它允许我们从Mongoose端关闭MongoDB连接。使用这个方法,我们可以强制关闭连接。让我们通过一个示例来了解 close() 方法

语法:

connection.close( force, callback );

参数: 此方法接受两个参数,如下所述:

  • force: 用于指定是否强制关闭连接。
  • callback: 用于指定回调函数,在关闭连接后执行。

返回值: 如果我们不提供任何回调函数作为方法的参数,此方法返回一个 promise。

设置Node.js Mongoose模块:

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

npm init

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

npm install mongoose

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

Mongoose Schema Connection.prototype.close()函数

数据库结构: 数据库的结构将看起来像这样,以下数据库存在于MongoDB中。

Mongoose Schema Connection.prototype.close()函数

示例1:

下面的示例说明了Mongoose模式close()方法的功能。我们可以注意到,在关闭连接后,无法在数据库中创建任何集合。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}) 
  
connectionObject.close(true, (error, result) => { 
    if (error) { 
        console.log('error', error); 
    } else { 
        console.log('Connection Closed successfully'); 
    } 
}) 
  
const Customer = 
    connectionObject.model('Customer', new mongoose.Schema({ 
        name: String, 
        address: String, 
        orderNumber: Number, 
    }));

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

node app.js

输出:

Connection Closed successfully

示例2: 下面的示例演示了Mongoose Schema的 close() 方法的功能。然而,当我们对 close() 方法行进行注释时,我们可以很容易地注意到现在集合已经在数据库中创建。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}) 
  
// connectionObject.close(true, (error, result) => { 
//   if(error) { 
//     console.log('error', error); 
//   } else { 
//     console.log('Connection Closed successfully'); 
//   } 
// }) 
  
const Customer = 
    connectionObject.model('Customer', new mongoose.Schema({ 
        name: String, 
        address: String, 
        orderNumber: Number, 
    }));

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

node app.js

输出:

数据库结构: 数据库的结构将如下所示,以下数据库存在于MongoDB中。

Mongoose Schema Connection.prototype.close()函数

参考: https://mongoosejs.com/docs/api/connection.html#connection_Connection-close

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程