N
N
NZ012021-01-06 10:04:20
JavaScript
NZ01, 2021-01-06 10:04:20

How to process data from database?

Hello I am new to Node js.
I took the data from Mongo DB as an array and passed it to the page, but here EJS complains about the forEach function, supposedly it is not a function.

Full text of the error:

TypeError: D:\js\views\index.ejs:15
    13|     <!-- тут должны отображатся элементы из коллекций todos -->

    14| 

 >> 15|     <% todos.forEach(function(todos) {%>

    16|             <strong><%= todos.title %></strong>

    17|             <%= todos.text %>

    18|     <% }) %>


todos.forEach is not a function


The code:

var express = require('express')
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient

var app = express()

var urlencoderParser = bodyParser.urlencoded({ extended: false })

app.set('view engine', 'ejs');

app.use('/public', express.static('public'))

var db
var users
var todos

var MongoServer = new MongoClient("mongodb://localhost:27017/", { useNewUrlParser: true, useUnifiedTopology: true });
MongoServer.connect(function(err, client){
    db = client.db("NZcoder")
    users = db.collection('users')
    todos = db.collection('todos')

    if(err){
        return console.log(err);
    }

    console.log("Подключение к базе данных MongoDB успешно")
});

app.get('/', function(req, res) {
    res.render('index', {todos: todos.find().toArray()})
})

var port = 3000

app.listen(port, function() {
    console.log(`Сервер запустился в порте: ${port}`)
})


How to decide?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Israfil22, 2021-01-07
@NZ01

todos.find() - returns a pointer - Cursor.
toArray() is an asynchronous method - it returns a promise.

app.get('/',  async (req, res) => {
    res.render('index', {todos: await todos.find().toArray()})
})

Link to doc
Scroll down to: toArray(callback) => {Promise}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question