更新文档时如何捕获猫鼬错误

How to catch mongoose errors when updating a document

在我的 Node.js 后端中,我有一个用于更新用户配置文件信息的端点。如果新电子邮件已在数据库中,我想向用户发送错误响应。但是,尽管我已经设置了 try-catch,但我仍然无法捕捉到错误。相反,服务器只是崩溃并显示以下 mongoose 错误消息。我在前端收到一个错误响应,但是在错误发生很长时间之后。非常感谢所有有用的建议。

(node:11864) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: testing.users index: email_1 dup key: { : "test@gmail.com" } ... (node:11864) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

UpdateProfile 在 UserController.js

updateProfile: (id,fname,lname,email,mobile,address,next) => {
  let args = {fname,lname,email,mobile,address}        
  try{
    User.findOneAndUpdate({ "_id": id }, 
      { "$set": Utils.removeNullsFromObject(args)},
      {new: true, useFindAndModify: false}).then(function(updatedUser, err){
          if(err) {
            console.log(err);
            next(err,null)
          } else {
            next(null,updatedUser)
          }
    );
  }
  catch(err){
    console.log(err);
    next(err,null)
  }
}

Try...catch 将与 async/await 一起使用,而不是与 promise...then 一起使用。 promise...then 有一个叫做 catch 的特殊块,可以用作,

updateProfile: (id,fname,lname,email,mobile,address,next) => {
  let args = {fname,lname,email,mobile,address}        
    User.findOneAndUpdate({ "_id": id }, 
      { "$set": Utils.removeNullsFromObject(args)},
      {
         new: true, useFindAndModify: false
    }).then(updatedUser => {
         next(null,updatedUser)
     ).catch(err =>{
       console.log(err);
       next(err,null)
    })
}

如果您想使用 async/await,那么,

updateProfile: async (id,fname,lname,email,mobile,address,next) => {
  let args = {fname,lname,email,mobile,address}    
    try{
     const updatedUser =  await User.findOneAndUpdate({ "_id": id }, 
      { "$set": Utils.removeNullsFromObject(args)},
      {
         new: true, useFindAndModify: false
    })
    next(null,updatedUser)
    } catch(err) {
       console.log(err);
       next(err,null)
    })
}

更详细的可以参考https://javascript.info/promise-error-handling