Query.prototype.catch() 如何在Mongoose中工作?
Query.prototype.catch()函数执行查询并返回一个 Promise,该 Promise 可以通过 doc(s) 解决或因错误而被拒绝。
句法:
Query.prototype.catch()
参数:该函数有一个参数,即拒绝回调函数。
返回值:此函数返回一个承诺。
安装mongoose:
npm install mongoose
安装mongoose模块后,您可以使用命令在命令提示符下检查您的mongoose版本。
npm mongoose --version
之后,您可以创建一个文件夹并添加一个文件,例如 index.js,如下所示。
数据库:这里使用的示例数据库如下所示:
示例 1:
index.js
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
const promise = User.find({age:"Not a number"});
promise.catch(function(error) {
console.log("Error Occurred:", error.message)
})
index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
const promise = User.find({ age: "Not a number" });
promise.catch(function(error) {
console.log("Error Occurred:", error.message)
})
app.listen(3000, function(error ) {
if(error) console.log(error)
console.log("Server listening on PORT 3000")
})
项目结构将如下所示:
使用以下命令运行index.js文件:
node index.js
输出:
Error Occurred: Cast to Number failed for value
"Not a number" at path "age" for model "User"
示例 2:
index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
const promise = User.find({ age: "Not a number" });
promise.catch(function(error) {
console.log("Error Occurred:", error.message)
})
app.listen(3000, function(error ) {
if(error) console.log(error)
console.log("Server listening on PORT 3000")
})
项目结构将如下所示:
使用以下命令运行index.js文件:
node index.js
输出:
Server listening on PORT 3000
Error Occurred: Cast to Number failed for value
"Not a number" at path "age" for model "User"
参考: https://mongoosejs.com/docs/api/query.html#query_Query-catch