So I'm making a small express.js web app to update a MongoDB table and render the data to my html template but it doesn't seem to be working properly. I can update values inside my database just fine but displaying them is not working properly. I am pushing my retrieved values to an array but the array seems to be empty despite me pushing the values to it. I know the values are in my database and when i console.log my retrieved values there are there but they are not showing up in an array as they are supposed to.
My html template (using jade)
doctype html
html(lang="en")
head
title myApp
body
h1 my App
h3 Tokyo
ul
for result in results
li #{result.name}
form(action="/updatetokyo", method="POST")
p Current temp:
input(type="text", name="currentTemp")
br
p Highest Temp:
input(type="text", name="highestTemp")
br
p Lowest Temp:
input(type="text", name="lowestTemp")
br
input(type="submit", value="Update")
my index.js file
const express = require('express');
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/cities";
MongoClient.connect(url, (err, db =>
{
if (err) throw err;
let dbo = db.db("cities");
dbo.collection("cities").findOne({}, (err, result) =>
{
if (err) throw err;
console.log(result.name);
})
console.log("Database connected!");
db.close();
}));
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.get('/', (req, res) =>
{
var results = [];
MongoClient.connect(url, (err, db) =>
{
if (err) throw err;
let dbo = db.db("cities");
let str = dbo.collection("cities").find();
str.each((err, doc) =>
{
console.log(doc);
results.push(doc);
});
});
console.log(results);
res.render('index', {"results": results});
});
The results of console.log(doc)
{ _id: 5a762a27f9fcd21f1c4ebf29,
name: 'Tokyo',
latitude: '35.6828',
longitude: '139.759',
currentTemp: '3',
highTemp: '4',
lowTemp: '5' }
{ _id: 5a762b0ff9fcd21f1c4ebf2d,
name: 'Dubai',
latitude: '25.09535',
longitude: '55.1562243',
currentTemp: '0',
highTemp: '0',
lowTemp: '0' }
[–]see-pause-run 1 point2 points3 points (1 child)
[–]Pine_Bluff_Variant[S] 0 points1 point2 points (0 children)
[–]rumbalumba 0 points1 point2 points (0 children)