Mongoose Schema.prototype.plugin()函数
使用Mongoose模式的API .prototype.plugin()方法是用在模式对象上的。它允许我们为模式创建插件。通过插件,我们可以为多个模式使用相同的逻辑。让我们通过一个示例来了解plugin()方法。
语法:
schemaObject.plugin( <callback_function>, <options> );
参数: 该方法接受以下两个参数:
- callback: 用于指定回调函数。
- options: 用于识别不同的属性。
返回值: 该方法没有返回任何值。
设置Node.js Mongoose模块:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目结构将如下所示:
示例1: 下面的示例演示了Mongoose模式插件(plugin())方法的功能。我们在模式对象上访问了()方法。
文件名: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 customerSchema = new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
});
customerSchema.plugin((schema => {
console.log(schema.pathType('address')) }))
const Customer = connectionObject
.model('Customer', customerSchema);
运行程序的步骤: 在项目的根目录下执行以下命令来运行应用程序:
node app.js
输出:
real
示例2: 下面的示例演示了Mongoose Schema插件()方法的功能。我们在模式对象上访问required paths()方法。该方法将返回模式级别所需的字段数组。
文件名: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 studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true }
});
studentSchema.plugin((schemaObject => {
console.log(schemaObject.requiredPaths()) }))
const StudentModel = connectionObject
.model('Student', studentSchema);
运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
[ 'rollNumber', 'name' ]
参考: https://mongoosejs.com/docs/api/schema.html#schema_Schema-plugin
极客教程