简体   繁体   中英

Mongoose and Node error: cannot read property 'forEach' of undefined

I want to display all from my MongoDB into a table from my .ejs file. But I always get the error i wrote in my title..

Here is some code snippet:

this is my routing js file (users.js)

router.get ('/Benutzerverwaltung_Mitarbeiter', async (req, res) => {

    User.find(function (err, users) {

        // if there is an error retrieving, send the error.
        // nothing after res.send(err) will execute
        if (err)
            return res.send(err);
        res.json(users);
        res.render('Benutzerverwaltung_Mitarbeiter',{
            users: res.user
        });
    });
});

and this my .ejs file:

 <%- include('../routes/users.js'); %>
            <div>
                <table id="tabelle" class="cell-border"  class="table table-striped" cellspacing="0" class="table table-hover">
                    <thead>
                    <tr>
                        <th>UserID</th>
                        <th>Rolle</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                    <% users.forEach (function (user) { %>
                    <td><%user.username%></td>
                    </tr>
                    <td><%user.admin%></td>
                    <%});%>
                    </tbody>
                </table>
                </div>

I hope you can help me out :) Cheeres, Mert

Both res.json and res.render are "terminal" methods - you should really only use them once when you are "finished", never both in the same method.

I think in this case you are trying to return html, not json, so you want res.render . Try this modification:

User.find(function (err, users) {

    // if there is an error retrieving, send the error.
    // nothing after res.send(err) will execute
    if (err)
        return res.send(err);
    res.render('Benutzerverwaltung_Mitarbeiter',{
        users: users || []
    });
});

In users.js, inside the res.render callback, I spot a typo when you assign the users property.

Array prototype functions will always throw that error above if the variable that's supposed to hold the array is not defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM