Home > Enterprise >  Why mongoose find for await don't working?
Why mongoose find for await don't working?

Time:11-28

I want to display a page with attachments, as well as all emails that are subscribed to this attachment. But emails are displayed incorrectly. Sometimes an email is inserted into the field, which should be in the next field. And somewhere the field remains empty when there should be an email (this email is in another field). Then I decided to replace forEach with for await. But the situation has not changed. What's the trouble?

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 })
    }
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are mixing promises with callbacks - res.json will be executed before the inner callback for User.find has finished. You are probably looking for something like:

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 })
    }
})
  • Related