Mongoose Schema.prototype.pre()函数

Mongoose Schema.prototype.pre()函数

Mongoose Schema API pre() 方法用于向 mongoose Schema 方法中添加预处理钩子,并可用于执行预处理操作。

语法:

Schema.prototype.pre(methodName, options, callback)

参数: 它接受上述提到并以下所述的以下参数:

  • methodName: 它表示要应用预处理中间件的模式方法名称或方法名称的正则表达式。
  • options: 这是一个可选的mongoose对象,包含 options.documentoptions.query
  • callback: 这是一个接受参数next的回调函数。

返回类型: 它返回一个Schema对象作为响应。

创建Node应用程序并安装Mongoose:

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

mkdir folder_name
cd folder_name
npm init -y
touch main.js

步骤2: 在完成Node.js应用程序后,使用以下命令安装所需模块:

npm install mongoose

示例1: 在这个示例中,我们将使用这种方法来记录应用于mongoose查询的过滤器。

文件名:main.js

// Importing the module 
const mongoose = require('mongoose') 
  
// Creating the connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', 
    { 
        dbName: 'event_db', 
        useNewUrlParser: true, 
        useUnifiedTopology: true
    }, err => err ? console.log(err) 
        : console.log('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
personSchema.pre(/^find/, function (next) { 
    console.log(this.getFilter()); 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 20 
    }, 
    { 
        name: 'Nami', 
        age: 20, 
    }, 
    { 
        name: 'Zoro', 
        age: 35 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    await Person.insertMany(personsArray) 
    await Person.find({ name: "Luffy", age: 20 }) 
})()

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

node main.js

输出:

Mongoose Schema.prototype.pre()函数

使用MongoDB Compass的GUI表示数据库:

Mongoose Schema.prototype.pre()函数

示例2: 在这个示例中,我们将使用这种方法在将mongoose文档保存到MongoDB之前更新其名称。

文件名:main.js

// Importing the module 
const mongoose = require('mongoose') 
  
// Creating the connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', 
    { 
        dbName: 'event_db', 
        useNewUrlParser: true, 
        useUnifiedTopology: true
    }, err => err ? console.log(err) 
        : console.log('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
personSchema.pre('save', function (next) { 
    if (this.name === 'Luffy') { 
        this.name = 'Nami'
    } 
  
    next() 
}); 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    const person = new Person({ name: 'Luffy', age: '19' }) 
    await person.save() 
})()

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

node main.js

使用MongoDB Compass的数据库的GUI表示:

Mongoose Schema.prototype.pre()函数

参考: https://mongoosejs.com/docs/api/schema.html#schema_Schema-pre

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程