"Encountering a Type Error in Express.js When Trying to Import Database Schema

Currently working on a small web app using the MEAN stack and going through the process of moving my schemas to a separate "models" directory. Everything runs smoothly when the schemas are within the same app.js file, but once I organize them into a modular file and import them, I encounter the following error:

TypeError: Player.find is not a function
at /Users/username/code/express/WebApp/v3/app.js:57:12

This issue arises specifically when it reaches the first route that requires looking up players, and despite hours of staring at the code, I'm unable to pinpoint what's causing this error.

Snippet from my app.js file:

var express    = require("express"),
    app        = express(),
    bodyParser = require("body-parser"),
    mongoose   = require("mongoose"),
    Player     = require("./models/players")

const port     = 3000;

mongoose.connect("mongodb://localhost/players", { useNewUrlParser: true, useUnifiedTopology: true });
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));

// PLAYER SCHEMA WAS ORIGINALLY DEFINED HERE BUT NOW ATTEMPTING TO MOVE TO A DIFFERENT DIRECTORY & IMPORT
/*var playerSchema = new mongoose.Schema({
    player: String,
    position: String,
    description: String
});
var Player = mongoose.model("Player", playerSchema);*/

app.get("/", function(req, res) {
    res.render("landing");
});

app.get("/players", function(req, res) {
    // Retrieving all players from the database
    Player.find({}, function(err, allPlayers){
        if(err){
            console.log(err);
        } else {
            console.log("Everything is fine.");
            res.render("players", {players: allPlayers});        
        }
    });
});

Below is my player.js file that I'm trying to import:

var mongoose   = require("mongoose");

var playerSchema = new mongoose.Schema({
    player: String,
    position: String,
    description: String
});


// Compiling into a model
module.exports = mongoose.model("Player", playerSchema);

The schema and model definitions work perfectly when they're in the app.js file directly, but seem to fail upon importing. Can anyone shed light on what might be missing here? Your assistance is greatly appreciated.

Answer №1

It appears that there is an issue with the file name in your require statement. The correct syntax should be:

const Player = require('../models/player')

Since your file name is player.js, not players.js and assuming you have stored the js file in a model folder, make sure to understand how to navigate using the file path.

/ signifies going back to the root folder, then moving forward/downwards.

./ indicates starting in the current folder and moving forward/downwards.

../ denotes going up one directory, then beginning the traversal.

Additionally, your backend structure should resemble this: Backend File Management

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

Configuring proxy settings in npm-yeoman package

I'm currently developing my Angular application using Yeoman. I've configured proxies and registry settings as shown below: npm config set proxy http://proxy.tcs.com:8080 npm config set https-proxy http://proxy.tcs.com:8080 npm config set reg ...

Utilize NodeJS to dynamically alter the text outputted on an HTML page

For educational purposes, I am designing a website where users can sign in by entering their name on the login page. After signing in, they will be redirected to the home page which displays a personalized welcome message using their name. I have included ...

Encountering an issue with multi ./src/styles.scss during the deployment of my Angular application on Heroku

My attempt to deploy my Angular app on Heroku is resulting in an unusual error. I've experimented with changing the styles path in angular.json, but it hasn't resolved the issue. I suspect it's a path problem, yet I can't seem to corre ...

What is the process for debugging a project that is not the "main" one?

I am facing an issue with Visual Studio Code where I have two directories in my workspace, both of which are node.js projects. However, I am only able to launch one of them for debugging. Even though both folders have a launch.json file, only the first fol ...

Error Handling with NPM and Rails in BrowserifyRails

Trying to launch a local application using ruby on rails has been a bit of a challenge. Initially, when attempting to start the local server, it raised an issue regarding nodejs, despite having successfully installed it. Now, the latest error message encou ...

Integrating social login using vue-authenticate with passport in a Node.js environment

I've been working on integrating Facebook login with vue-authenticate and passport. Successfully logged into my Facebook account, I obtained the 'Callback code' as well. Here is my callback URL: http://localhost:8080/auth/callback?code=AQD0 ...

Node.js and Express: Associating uploaded files with the correct user account

What method would you recommend for linking file uploads to the user who uploaded them? I have been considering using a mongoose model for file uploads with a schema structure similar to this: uploader: {type: Schema.Types.ObjectId, ref: 'User' ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Feeling puzzled about the next() function in Node.js?

https://github.com/hwz/chirp/blob/master/module-5/completed/routes/api.js function isAuthenticated (req, res, next) { // If the user is authenticated in the session, call the next() to proceed to the next request handler // Passport adds this met ...

Leveraging Promises for Concurrent In-Memory Processing

We are currently working on a project that involves processing approximately 5,000 objects, with each object requiring between 200-500 milliseconds to process. One of the developers on our team has suggested utilizing promises to handle the concurrent proc ...

Encountered an issue in Docker for Windows OS: "ERROR: Unable to retrieve https://gcr.io/v2/: x509: certificate signed by unknown authority"

I'm in the process of setting up an application that has Python and GraphQL as the backend, along with Redis. While trying to build Nginx using ' docker-compose --profile backend --profile frontend up --build ' it keeps pulling Redis but ...

Getting the error code from eslint while running in a pre-commit hook - what's the solution?

In the .git/hooks/pre-commit file of my project, I have the following script: npx eslint --max-warnings 1 --exit-on-fatal-error $(git diff --name-only HEAD **/*.ts | xargs) status=$? if [ $status -eq 0 ] then echo "Good" exit 2 fi if [ $status -eq 1 ...

Creating a custom regular expression in ExpressJS: matching a parameter to all routes except for one

My current route is set up to catch the code param in the following way: app.get('/:code([a-zA-Z]{3})', codeHandler); This setup successfully matches all three-letter codes, but now I want to modify it to exclude one specific code. For example, ...

Guide on adding logout feature with jsonwebtoken in node.js

One common approach is to delete the browser's cookie first. However, I am interested in learning how to destroy tokens from the server side or how to verify logout functionality from the server side. ...

Frontend utilizing the Next-auth Github Provider for Profile Consumption

After following the official documentation for implementing SSO with the Next-auth Github provider in my App, I encountered an issue where the Client API documentation suggested using useSession() to retrieve session information, but it was not returning t ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Query about Javascript/Node/JSON - why isn't this functioning properly?

I thought I had a good grasp on what I was doing until the process started getting jumbled. My code is being executed through Node, not a web browser. For some reason, it jumps to the prompt at the end of the while loop first and I'm not sure why tha ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

Why is it that all my workers in node.js respond to a single incoming request?

In my current setup, I am utilizing node in combination with express as the web server, operating with a total of 4 workers within a cluster. The issue arises when an incoming request triggers responses from all workers. Each worker serves the same web ap ...