Mongoose Document Model.prototype.collection函数
Mongoose API中的Model.prototype.collection属性用于显示与任何模型相关的集合信息。它展示了模型正在使用的集合。 Model.prototype.collection属性是只读属性,对该属性的修改不起作用。
语法:
Model_Name.collection
返回值: Model.prototype.collection 属性返回一个带有嵌套对象和属性数量的对象。
设置 Node.js 应用程序:
步骤1: 使用以下命令创建一个 Node.js 应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将会如下所示:
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个名为userSchema的模式,包含两个列或字段“name”和“age”。最后,我们使用User模型上的collection属性,它将返回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, age: Number }
)
// Defining userSchema model
const User = mongoose.model('User', userSchema);
const output = User.collection
console.log(output)
程序运行步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在studentSchema上定义了一个模型,它包含四个列或字段(“name”、“age”、“city”和“state”)。最后,我们使用Student模型上的collection属性,该属性将返回由Student模型使用的集合。
- 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 studentSchema = new mongoose.Schema(
{ name: String, age: Number, city: String, state: String }
)
// Defining studentSchema model
const Student = mongoose.model('Student', studentSchema);
const output = Student.collection
console.log(output)
运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
参考: https://mongoosejs.com/docs/api/model.html#model_Model-collection