1sa4c
1sa4c

Reputation: 87

.forEach() in EJS and Mongoosse

I'm trying to show every author stored in a mongo db in an ejs file. My idea was to iterate over every author using Model.find({})

authorController.js

const express = require('express')
const router = express.Router()
const Author = require('../models/Author')


router.get('/', async (req, res) => {
    try{
        const authors = Author.find({})
        res.render('authors/index', {authors: authors})
    } catch(error) {
        res.redirect('/')
    }
})

index.ejs

<h1>Search authors</h1>

<form action="/authors" method="GET">
    <label>Name</label>
    <input type="text" name="name">
    <button type="submit">Search</button>
</form>

<% authors.forEach(author => { %>
    <div class="author"><%= author.name %></div>
<% }) %>

The Author model

const mongoose = require('../database')

const AuthorSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    }
})

module.exports = mongoose.model('Author', AuthorSchema)

It raises the error: authors.forEach is not a function

I've read a bit and I think this is happening because I can´t iterate over an object using forEach(). How can I do it so?

Upvotes: 0

Views: 487

Answers (1)

The Alpha
The Alpha

Reputation: 146219

In your code (within the async function), the following line:

const authors = Author.find({});

Should be like this:

const authors = await Author.find({});

Upvotes: 2

Related Questions