0

I am using express js, and mongoose for fetching data from collection and store it in a list and then send it to an ejs file. But I don't know why the data is not getting stored in list. below are my code.

app.get("/", (req, res) => {
  
    let item =  [];
    General.find(null, (err, data)=>{
            if(err){
              console.log(err); 
            } else {
                data.forEach(element => {
                    item.push(element.name);
                });
                console.log("pushed "+item);                 
            }
        });

    console.log("final  "+item);
    res.render("index", { title: "Welcome", list: item});
});

this is what printed in console when I run the above program.

listening 3000
final
pushed item-1,item-2

Here is my DB Collection

[
  { _id: ObjectId("63d165717d847e937728e63b"), name: 'item-1', __v: 0 },
  { _id: ObjectId("63d165857d847e937728e63e"), name: 'item-2', __v: 0 }
]

Here are my configurations

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

mongoose.set("strictQuery", false);
mongoose.connect("mongodb://127.0.0.1:27017/todolistDB", { useNewUrlParser: true });
const genSchema = new mongoose.Schema({ name : String });
const General = mongoose.model("General", genSchema);

const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: "true" }));
app.use(express.static("public"));

I don't understand why is my final item list is empty.

  • `find` is async. It *(almost certainly)* completes after `render` is called. – Dave Newton Jan 25 '23 at 18:07
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Dave Newton Jan 25 '23 at 18:08

1 Answers1

0

You have to wait for General.find because find method returns a Promise. Also check your logs, pushed is printed after final that shows you that your find method is an async function.

app.get("/", async (req, res) => {
  
    let item =  [];
    await General.find(null, (err, data)=>{
            if(err){
              console.log(err); 
            } else {
                data.forEach(element => {
                    item.push(element.name);
                });
                console.log("pushed "+item);                 
            }
        });

    console.log("final  "+item);
    res.render("index", { title: "Welcome", list: item});
});
Diego
  • 124
  • 2