我有以下代码:

exports.dashboardUpdateNote = async (req, res, next) => {
    var updateNote = {
        "title": req.body.title,
        "body": req.body.body1,
    }
    await Note.findOneAndUpdate({ _id: req.body.note_id }, { $set: updateNote })
        .then((Successful) => {
            console.log('Successful: ', Successful)
        })
    return res.redirect('/dashboard')
}

它已重定向,但未发生更改(更新). 然后,我在代码中进行了以下更改(添加:{upsert:true}):

exports.dashboardUpdateNote = async (req, res, next) => {
    var updateNote = {
        "title": req.body.title,
        "body": req.body.body1,
    }
    await Note.findOneAndUpdate({ _id: req.body.note_id }, { $set: updateNote }, { upsert: true })
        .then((Successful) => {
            console.log('Successful: ', Successful)
        })
    return res.redirect('/dashboard')
}

它重定向并发生了更改(更新),但当我单击我已更新的(备注)以查看它时,它给出了这个错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:399:5)
    at ServerResponse.setHeader (node:_http_outgoing:644:11)
    at ServerResponse.header (C:\Users\hp\NODE\Notes\node_modules\express\lib\response.js:794:10)     
    at ServerResponse.contentType (C:\Users\hp\NODE\Notes\node_modules\express\lib\response.js:624:15)
    at ServerResponse.send (C:\Users\hp\NODE\Notes\node_modules\express\lib\response.js:149:14)       
    at done (C:\Users\hp\NODE\Notes\node_modules\express\lib\response.js:1035:10)
    at tryHandleCache (C:\Users\hp\NODE\Notes\node_modules\ejs\lib\ejs.js:280:5)
    at exports.renderFile [as engine] (C:\Users\hp\NODE\Notes\node_modules\ejs\lib\ejs.js:491:10)     
    at View.render (C:\Users\hp\NODE\Notes\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\hp\NODE\Notes\node_modules\express\lib\application.js:657:10)

但是当我点击一个我从来没有更新过的笔记来查看它时,没有错误发生,笔记出现了. (我忘了写,必须更新的注释实际上没有更新,它添加了另一个新注释,所以每次更新后注释都会增加一个. )

推荐答案

您混合了awaitthen块,并且没有任何错误处理,因此您不知道保存文档时是否出错.您收到的实际错误是在发送响应后何时try 发送响应,通常超出您不考虑的或未返回的块作用域.

findOneAndUpdate方法接受一个更新文档作为第二个参数,因此只需传递updateNote对象,Mongoose将为您更新titlebody属性.

完成的函数可能如下所示:

exports.dashboardUpdateNote = async (req, res, next) => {
   try{
      console.log(req.body); //< make sure you have parsed data in req.body
      const updateNote = {  //< use const instead of var
        title: req.body.title,
        body: req.body.body1,
      }
      const doc = await Note.findOneAndUpdate({_id: req.body.note_id}, 
         updateNote, 
         {new: true}  //< return the updated document
      );
      if(!doc){ //< doc will be null if no document was found
         return res.status(400).json({
            message: 'No document found.'
         });
      }
      // Document was updated so return to dashboard
      console.log('Successful: ', doc)
      return res.redirect('/dashboard')
   }catch(err){
      console.log(err)
      // Handle the error
      return res.status(500).json({
           message: 'Error on server.'
      });
   }
}

Node.js相关问答推荐

node 模块错误:类型参数OT具有循环约束''

nest js控制器方法调用两次

node 上的磁盘压力

如何在Mongoose for MongoDB中编写此查询

在 NodeJS 中使用 post 时出现错误 500TypeError: 无法解构 'req.body' 的属性 'name',因为它未定义

PM2 是否需要成为其托管项目的依赖项?

几个 lambda 共有的函数

Postgressql的BIGSERIAL自增序列,即使由于唯一约束错误没有创建行,也会自动增加

未授权使用联合身份未授权用户角色从 Amplify graphQL 访问类型 Y 上的 X

如何使用对象中的常量值验证字符串字段?

为什么我的 Cypress Post 请求的请求正文是空的?

在系统启动时启动本地 node 服务器

React Native:执行 com.android.build.gradle.internal.tasks.Workers$ActionFacade 时发生故障

将 express js app.use() 移动到另一个文件

Express.js - 监听请求中止

如何监控 node.js 上的网络,类似于 chrome/firefox 开发者工具?

Heroku + Node:找不到模块错误

在 Node.js 中混合使用 JavaScript 和 TypeScript

在 Node.js 上使用 Connect 无法获取 /

什么时候应该将函数存储到变量中?