當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。