Mongoose/Node How to access DB in directly in EJS file Mongoose/Node How to access DB in directly in EJS file mongoose mongoose

Mongoose/Node How to access DB in directly in EJS file


Database requests shouldn't be performed directly in view. This is prescribed by separation of concerns principle that stands behind MV* patterns.

Express route handlers act as MVC controllers, their purpose is to provide data from models to views.

Mongoose supports promises, so using callback-based API just complicates everything. Common data like could be provided as a separate function that returns a promise of data, e.g.:

function getPageData() { ... }async function routeHandler(req, res, next) {  try {    const pageData = await getPageData();    res.render('index', {      ...pageData,      / * etc */    });  } catch (err) {    next(err);  }};

routeHandler itself can be refactored to helper function that accepts view, view variables, req, res, and next.

Another approach is to make page data available globally in all or most views with additional middleware, as described in this related question, e.g.:

app.use(async function (req, res, next) {  try {    const pageData = await getPageData();    Object.assign(res.locals, pageData);    next();  } catch (err) {    next(err);  }});