当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Mongoose Query.prototype.catch()用法及代码示例

Mongoose 查询API.prototype.catch()方法Mongoose API 的函数用于查询对象。它允许我们执行查询返回的承诺。使用此方法,我们可以处理拒绝的 Promise 错误,并可以显示它或将其用于后续流程。可以使用 Promise 来处理被拒绝的处理程序catch()块或方法。让我们了解一下catch()使用示例的方法。

用法:

promiseObject.catch( reject );

参数:此方法接受单个参数,如下所述:

  • reject:它用于指定被拒绝的承诺处理程序。

返回值:该方法返回可以使用回调函数处理的承诺。

设置 Node.js Mongoose 模块:

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

npm init

步骤 2:创建 NodeJS 应用程序后,使用以下命令安装所需的模块:

npm install mongoose

项目结构: 项目结构将如下所示:

数据库结构:数据库结构如下所示,以下数据库存在于 MongoDB 中。

示例 1:下面的示例说明了 Mongoose Connection 的基本函数catch()方法。在此示例中,promise 已得到解决,这就是代码执行尚未进入 catch 块的原因,并且我们正在从集合中获取所有文档。

文件名:app.js

Javascript


// 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.find().then(res => { 
    console.log(res); 
}).catch(error => { 
    console.log('Error', error) 
});

运行程序的步骤:要运行应用程序,请从项目的根目录执行以下命令:

node app.js

输出:

[
  {
    _id: new ObjectId("63c2fe2ef9e908eb17f225da"),
    name: 'Student1',
    age: 25,
    rollNumber: 36,
    __v: 0
  },
  {
    _id: new ObjectId("63c2fe2ef9e908eb17f225db"),
    name: 'Student2',
    age: 18,
    rollNumber: 65,
    __v: 0
  },
  {
    _id: new ObjectId("63c2fe2ef9e908eb17f225dc"),
    name: 'Student3',
    age: 15,
    rollNumber: 36,
    __v: 0
  }
]

示例 2:下面的示例说明了 Mongoose Connection 的基本函数catch()方法。在此示例中,Promise 已被拒绝,这就是代码执行进入 catch 块的原因,并且我们收到了预期的错误和错误消息。

文件名:app.js

Javascript


// 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.update( 
    { name: "Student1" }, 
    { age: 'Eight' } 
).then(res => { 
    console.log(res); 
}).catch(error => { 
    console.log('Error', error) 
});

运行程序的步骤:要运行应用程序,请从项目的根目录执行以下命令:

node app.js

输出:

Error CastError: Cast to Number failed for value "Eight" (type string) at path "age"

参考:https://mongoosejs.com/docs/api/query.html#query_Query-catch



相关用法


注:本文由纯净天空筛选整理自sakshio0hoj大神的英文原创作品 Mongoose Query.prototype.catch() API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。