我使用 Koa.js、mongodb 和 momgoose.js
我的客户端有一个简单的表单,我有一些独特且必需的输入。 当我提交我的表单时,我尝试将这些数据保存在我的 Schema 中的 mongodb 中。
const mySchema = mongoose.Schema(
{
firstname: {
type: String,
unique: true,
required: true
},
lastname: {
type: String,
required: true
}
});
const My = mongoose.model('My', mySchema);
保存函数
function addDB(data) {
return new Promise(() => {
const bar = new My({ ...data });
bar.save().then(() => console.log('success'));
});
我怎样才能像这样在数据库中捕获错误:
UnhandledPromiseRejectionWarning: ValidationError: My validation failed: lastname: Path `lastname` is required.
最佳答案
您可以使用 catch
处理错误以避免此错误:
function addDB(data) {
return new Promise(() => {
const bar = new My({ ...data });
bar.save().then(() => console.log('success')).catch(err=>console.log(err))
});
关于javascript - 错误处理 promise 在 mongoDB 中保存唯一数据(ValidationError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51245713/