When breaking down code in models, Node.js may display a `var undefined`

As I embark on my journey of creating my first nodejs app, I encountered an error when attempting to transfer a portion of my code to an external JavaScript file. The specific piece of code I am trying to move is the mongodb schema declaration:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//--------------------users ------------
var usersSchema = new Schema({
    email: String,
    name: String, 
    phoneNumber: String, 
    BirthDate: Date, 
    loginpwd:String
});

var UserModel = mongoose.model('users', usersSchema);

To load the external file, I am utilizing the filesystem module:

fs.readdirSync(__dirname+'/models').forEach(function(filename){
    if (~filename.indexOf('.js')) 
        require(__dirname+'/models/'+ filename);
    console.log(filename+" added");
});

However, upon separating the code, a problem arises where I receive an "undefined UserModel" error:

var userData = new UserModel({email : req.body.edtEmail,
                                        name: req.body.edtName,
                                        phoneNumber: req.body.edtPhoneNumber,
                                        BirthDate: req.body.edtBirthDate,
                                        loginpwd: req.body.edtSenha});
// save user data to database
userData.save(function(err, record){
   if(err) throw err;

    // session setting
    req.session.userEmail = req.body.edtEmail;
    req.session.name = req.body.edtName;
    req.session.phoneNumber = req.body.edtPhoneNumber;
    req.session.birthDate = req.body.edtBirthDate;
    req.session.userId = record._id;
    res.redirect('/dashboard');
});

On the other hand, the following code functions properly whether it is inline or within the main file:

app.get('/users/json', function(req, res){
    mongoose.model('users').find(function(err, users){
        res.send(users);
    });
 });

I wonder if I am making an error in loading the external file or perhaps overlooking something significant?

Answer №1

NodeJs provides a built-in system for loading files.

If you're unsure of what to do, in nodejs you can follow this example:

//Let's say this file is named UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//-------------------- rest of your code ------------

var UserModel = mongoose.model('users', usersSchema);
module.exports = UserModel; //this step is crucial

Then in another file, you can simply load this:

var UserModel = require('UserModel'); 
var bob = new UserModel({ .... 

This way, you can utilize your UserModel. It might be helpful to read the documentation on require function.

Answer №2

One possible way to implement is:

In the schema file: (for example, in the directory "models/userModel.js")

...
mongoose.model('UserModel', usersSchema);

In the controller or any other file where you need to use it: (e.g., in the directory "controller/userController.js")

require('../models/userModel');// load user model
var mongoose = require('mongoose'),
    UserModel = mongoose.model('UserModel'),

var userData = new UserModel({email : req.body.edtEmail, //rest of code...});

userData.save(function(err, record){ //rest of code ...

You can also set up a route like this: (similar to how it's done for the controller)

app.get('/users/json', function(req, res){
    UserModel.find(function(err, users){
        res.send(users);
    });
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jest encountered an error with mock fs, stating "cannot find file or directory to list" and indicating that mock_fs_1.default is not a valid function

I'm working on loading a config file using jest and attempting to set up a folder for an integration test using the mock-fs library. However, I encountered this error: Error: no such file or directory, lstat : 'path to one of another folder in ...

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

How can one efficiently delete on express without having to specify the entire route every time?

Express allows me to create a route like the following: app.delete('/items/:id', function (req,res) { ... }) When I send a delete request to http://localhost/items/10, the item is successfully deleted. However, when attempting to send a delete ...

Error connecting to the database occurred due to a network issue with Mongodb on the initial attempt

I am attempting to establish a connection to mongodb atlas but encountering an issue. MongoNetworkError: failed to connect to server [accounting-shard-00-01-6tg4q.mongodb.net:27017] on first connect [MongoNetworkError: connection timed out] mongoose .c ...

Having trouble displaying iframe: the parent element is in violation of the Content Security Policy directive "frame-ancestors 'none'"

Looking to embed an iframe from Github? Check out the code below: <iframe src="https://gist.github.com/user45445/9bf8d568e3350146ba302d7d67ad576f"> </iframe> The console is throwing this error: Refused to display 'https://gist.github.com ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

I keep encountering a 'Missing Permissions' issue whenever I attempt to execute the ban command in Discord.js. What could be causing this problem?

While working on coding a ban command for my Discord server, I encountered an issue where the command was not working as expected. Upon testing, I received an error message on the console stating DiscordAPIError[50013]: Missing Permissions. This was puzzli ...

Show data from MongoDB collection in an HTML page

Hey there, I'm a beginner when it comes to MongoDB. Currently, I am working on a website where I want to retrieve data from a MongoDB collection based on a {Name: String} field within that Collection and showcase it in an HTML Table. Here's wha ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

Enhance your website with multiple interactive elements by incorporating several flashes through ExpressJS

When using request.flash to send flash messages to users, I encountered an issue. It seems that request.flash does not allow me to send multiple flash messages to a view at once. This is the code I tried: request.flash('danger', 'some flas ...

Inject variables into the exports object

I need to pass a value from two files into a variable. How can I achieve this? Here is an example structure of the sample.js file: module.exports = { content: [ { table: { body: [ [ { text: a ...

I have successfully deployed my node and express app locally, but unfortunately, I encounter issues when trying to deploy it to Heroku

Apologies if this seems like a simple problem. I'm fairly new to working with Node + Express and still trying to grasp some key concepts! I've encountered an issue with my Node + Express app where it runs locally without any problems, but when I ...

Need to end all Node.js instances to properly reflect the code. Any solutions for resolving this issue?

After developing an application using typescript, hapi, and nodejs, I encountered a strange issue. Whenever I save, remove, or add new code, the changes are not reflected even after running gulp build. The only way to get it working is by closing all run ...

Angular 4 - Issues with route configurations

My Angular application is running smoothly on localhost:4200 using ng serve. The node server can be found at localhost:3000. After running ng build, a bundle file is generated and properly served from localhost:3000 thanks to the line app.use(express.sta ...

Gatsby 3 encountered a failure during the `gatsby build` process while trying to build static HTML pages, resulting in an error related to `WebpackError: ReferenceError: ... is not defined` specifically referring to the firebase/app module

Encountering an issue with Gatsby v3 when running gatsby build. Providing some context... The problem arises due to firebase modules being included in a custom hook (code snippet below). A custom webpack config function in gatsby-node is used with the we ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...

Encountering issues while attempting to run npm install following the update of the node version to 14

Recently, I have upgraded both my node and npm versions. The current versions are: Node: 14.15.4 Npm: 8.3.0 In my package.json file, the dependencies and devDependencies are as follows: "dependencies": { "bootstrap": "^4.3.1 ...

Having trouble accessing environment variable in NodeJS with ExpressJS

In my Express.js project, I have set a variable like this: app.set('HOST', 'demo.sample.com');. However, when I try to access this variable, I am getting undefined as the result. I am trying to retrieve the value using process.env.HOST. ...

NPM IP library susceptible to Server-Side Request Forgery (SSRF) vulnerabilities

Received Security Alert from GitHub's Dependabot Regarding an Issue in My Angular Repository A security vulnerability has been identified in all versions of the NPM package "ip," allowing a malicious actor to execute arbitrary code and access sensiti ...

After numerous successful uses, the bcrypt password in Mern stack suddenly fails to match

I've encountered a puzzling issue and haven't been able to find a solution on my own. Here's the situation: I'm developing a MERN stack social media application where registration and login functionalities were working fine initially. A ...