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.