TheShanachie
New Coder
In a current JS web application. I am currently rendering my pages with specific information from a MongoDB Atlas cluster. Unfortunately, I don't know enough about JS to fix a major issue. The current code queries the Database each time a page is rendered as far as I understand. This seems like a major issue for the speed of my app. I would like understand how these queries can be called and cached at the beginning of the web app so this doesn't have to happen again.
Code:const express = require('express'); const Link = require('./models/link'); const Site = require('./models/site'); const app = express(); const port = 3000; const dbURI = 'censored'; mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then((result) => app.listen(port)) .catch((err) => console.log(err)) const db = mongoose.connection; app.set('view engine', 'ejs'); app.use(express.static('public')); app.get('/', async (req, res) => { try { const [links, sites] = await Promise.all([ Link.find({}).sort({ order_no: 'asc' }), Site.find({}).sort({ order_no: 'asc' })]); res.render('index', { title: "Home", links, sites }) } catch (e) { console.log(e); res.sendStatus(500); } }); app.get('/page01', async (req, res) => { try { const [links, sites] = await Promise.all([ Link.find({}).sort({ order_no: 'asc' }), Site.find({}).sort({ order_no: 'asc' })]); res.render('page01', { title: "Home", links, sites }) } catch (e) { console.log(e); res.sendStatus(500); } }); app.get('/page02', async (req, res) => { try { const [links, sites] = await Promise.all([ Link.find({}).sort({ order_no: 'asc' }), Site.find({}).sort({ order_no: 'asc' })]); res.render('page02', { title: "Home", links, sites }) } catch (e) { console.log(e); res.sendStatus(500); } });