Mongoose Schema Connection.prototype.collections函数
Mongoose模式连接原型.collections API
Mongoose模式 API中的 Connection.prototype.collections 属性用于Connection对象。它允许我们获取与连接对象关联的集合的详细信息。每个连接对象显示了多少个集合,我们将以散列格式获取这些信息。让我们通过一个示例来了解 collections 属性。
语法:
connection.collections;
参数:
此属性不接受任何参数。
返回值:
此属性返回与连接对象关联的集合的散列信息。
设置Node.js Mongoose模块:
步骤1:
使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构:
项目的结构将会是这样的:
示例1: 下面的示例演示了Mongoose Connection collections属性的基本功能。由于我们定义了customer模型,collections属性只返回与之相关的信息。
文件名: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,
})
const Customer = connectionObject.model('Customer',
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
}));
const result = connectionObject.collections;
console.log(result);
运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:
node app.js
输出:
示例2: 下面的示例展示了Mongoose Connection的基本功能 collections 属性。在这个示例中,我们定义了两个模型 customer 和 student。 使用 collections 属性,我们可以获取这两个模型的信息。
文件名: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,
})
const Customer = connectionObject.model('Customer',
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
}));
const studentSchema = new mongoose.Schema({
name: {type: String, required: true},
age: Number,
rollNumber: {type: Number, required: true}
});
const StudentModel = connectionObject.model(
'Student', studentSchema);
const result = connectionObject.collections;
const obj = Object.keys(result);
console.log(obj);
运行程序的步骤: 要运行应用程序,请从项目的根目录执行下面的命令:
node app.js
输出:
[ 'customers', 'students' ]
参考资料: https://mongoosejs.com/docs/api/connection.html#connection_Connection-collections