【问题标题】:Why mongoose find for await don't working?为什么猫鼬寻找等待不起作用?
【发布时间】:2021-11-27 22:27:24
【问题描述】:

我想显示一个带有附件的页面,以及订阅此附件的所有电子邮件。但是电子邮件显示不正确。有时会在字段中插入一封电子邮件,该字段应该在下一个字段中。当应该有一封电子邮件(此电子邮件在另一个字段中)时,该字段仍然为空。然后我决定用 for await 替换 forEach。但情况并没有改变。有什么问题?

router.get('/', auth, async (req, res) => {
    try {
        await Attachment.find(async (err, attachments) => {
            let html_table = ""
            for await (const attachment of attachments) {
                html_table += "<tr>"
                html_table += "<td>"
                html_table += attachment.file_name
                html_table += "</td>"
                html_table += "<td>"
                console.log(attachment.id)
                await User.find({
                    attachments: attachment.id
                }, async (err, users) => {
                    for await (const user of users){
                        html_table += user.email + "<br />"
                        console.log(user.email)
                    }
                })
                html_table += "</td>"
                html_table += "</tr>"
            }
            res.json(html_table)
        })
    } catch (e) {
        res.status(500).json({ message: e.message })
    }
})

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    您将 promise 与回调混合在一起 - res.json 将在 User.find 的内部回调完成之前执行。您可能正在寻找类似的东西:

    router.get('/', auth, async (req, res) => {
        try {
            const attachments = await Attachment.find();
            let html_table = ""
            for (const attachment of attachments) {
                    html_table += "<tr>"
                    html_table += "<td>"
                    html_table += attachment.file_name
                    html_table += "</td>"
                    html_table += "<td>"
                    console.log(attachment.id)
                    const users = await User.find({
                        attachments: attachment.id
                    });
                    for (const user of users){
                          html_table += user.email + "<br />"
                          console.log(user.email)
                    }                    
                    html_table += "</td>"
                    html_table += "</tr>"
           }
           res.json(html_table);
        } catch (e) {
            res.status(500).json({ message: e.message })
        }
    })
    

    【讨论】:

    • 这对我有用。谢谢
    猜你喜欢
    • 2022-12-18
    • 2018-07-24
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2019-03-20
    • 2013-05-14
    相关资源
    最近更新 更多