【问题标题】:Mongoose asynchronous .save and callbackMongoose 异步 .save 和回调
【发布时间】:2018-04-08 14:59:36
【问题描述】:

这是您可以解释但不知道如何解决的问题之一。我有一个简单的store 方法:

exports.store = async (req, res) => {
    const mydata = new MyModel(req.body)
    await mydata.save(function(err,user) {
        res.location('/mydata/id/' + user._id)
    })
    res.status(201).json({ data: userdata })
}

当它运行时,我收到以下错误:

events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:489:11)
    at ServerResponse.setHeader (_http_outgoing.js:496:3)
    at ServerResponse.header (.../node_modules/express/lib/response.js:730:10)
    at ServerResponse.location (.../node_modules/express/lib/response.js:847:15)
    at .../src/controllers/users-controller.js:26:13
    at .../node_modules/mongoose/lib/model.js:3919:16
    at .../node_modules/mongoose/lib/services/model/applyHooks.js:162:20
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Process finished with exit code 1

我的回调函数似乎是单独异步运行的,因为res.status(201).json({ data: userdata }) 似乎正在产生错误并且不允许我设置位置标头。

我已经四处寻找如何设置位置标题,但没有一个答案像我想要做的那样。这似乎是以前应该做的事情......?我正在寻求有关如何执行此操作的帮助...

【问题讨论】:

    标签: asynchronous mongoose callback


    【解决方案1】:

    你混淆了两种思维方式:

    • 承诺(在您的情况下使用 async/await)
    • 回调

    只用一个


    try {
       const user = await mydata.save();
    
       res.location(`/mydata/id/${user._id}`);
    
       // Other stuff ...
    } catch(err) {
       // Handle the errors
    }
    

    here 你会收到一篇关于 Promises into mongoose 的文章。

    【讨论】:

    • 确实!我懂了!我不知道您可以将const user 放在右侧。我虽然为了访问user,你需要使用回调。效果很好!谢谢!
    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2017-10-09
    • 1970-01-01
    • 2018-01-17
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多