When it comes to my user registration process, I've encountered an issue
const express = require ('express');
const userRouter = express.Router ();
userRouter.get ('/', function getUserList (req, res) {
let User = require ('../models').User;
User.find ({}, function (err, list) {
res.json (list);
});
});
userRouter.post ('/', function createUser (req, res) {
let User = require ('../models').User;
if (req.body.username && req.body.password)
User.create (req.body, function (err, user) {
res.json (user);
});
});
... 3 more functions with the same `let User` ...
module.exports = userRouter;
Currently, in order to access the User module, I find myself having to use the require
function multiple times. I attempted to define the User variable as a global one at the beginning of my code like so:
const express = ..., userRouter = ...
var User = ...
However, despite this attempt, I am still unable to access the User variable inside my callbacks.
My question is: Is it common practice to repeatedly require the User module or am I overlooking something important?
edit: Upon further investigation, I noticed that the User variable remains undefined within the callback functions.