Mongoose Query.prototype.error()函数
Mongoose的 Query API.prototype.error() 方法是用于Query对象的。它允许我们获取和设置特定查询的错误函数和操作。该错误操作会在exec()方法完成其操作之前被执行。让我们通过一个示例来理解error()方法。
语法:
query.error( err );
参数: 该方法接受一个参数,如下所示:
- err: 用于指定错误对象。
返回值: 该方法返回一个可以使用回调函数的查询对象。
设置Node.js Mongoose模块:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 在创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目结构如下所示:
数据库结构: 数据库结构将如下所示,以下数据库存在于MongoDB中。
示例1: 下面的示例演示了Mongoose连接error()方法的基本功能。在这个示例中,我们提供了错误的字段名称,从而引发了错误,并且我们使用异步函数来处理Promise。
文件名称: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 }
});
const StudentModel = connectionObject.model('Student', studentSchema);
(async () => {
const result = await StudentModel.find(
{ num: "45221" })
.error(new Error("Woop !!, no such field exists"));
console.log(result);
})();
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
(node:18236) UnhandledPromiseRejectionWarning: Error: Woop !!, no such field exists
at D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API .prototype.error()\app.js:21:64
示例2: 下面的示例演示了Mongoose Connection的基本功能错误(error())方法。在此示例中,我们没有提供要更新的最新值,这导致出现错误,我们使用then和catch块来处理Promise。
文件名: 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 }
});
const StudentModel = connectionObject.model('Student', studentSchema);
StudentModel
.updateOne({ name: "45221" })
.error(new Error("Please put the updated values")).then(res => {
console.log(res);
}).catch(err => console.log(err));
运行程序步骤:
要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
Error: Please put the updated values
参考: https://mongoosejs.com/docs/api/query.html#query_Query-error