Encountered an Error in Express.js: Unable to POST /users

I am currently in the process of learning the MEAN stack by following a tutorial and have encountered an error. Unfortunately, I am having difficulty identifying exactly where I went wrong.

While attempting to test routes in Postman by creating a user, I consistently receive the message 'Cannot POST /users'.

Could someone provide assistance with this issue? Thank you in advance!

routes.js

// Dependencies
var mongoose        = require('mongoose');
var User            = require('./model.js');

// Opens App Routes
module.exports = function(app) {

    // GET Routes
    // --------------------------------------------------------
    // Retrieve records for all users in the db
    app.get('/users', function(req, res){

        // Uses Mongoose schema to run the search (empty conditions)
        var query = User.find({});
        query.exec(function(err, users){
            if(err)
                res.send(err);

            // If no errors are found, it responds with a JSON of all users
            res.json(users);
        });
    });

    // POST Routes
    // --------------------------------------------------------
    // Provides method for saving new users in the db
    app.post('/users', function(req, res){

        // Creates a new User based on the Mongoose schema and the post bo.dy
        var newuser = new User(req.body);

        // New User is saved in the db.
        newuser.save(function(err){
            if(err)
                res.send(err);

            // If no errors are found, it responds with a JSON of the new user
            res.json(req.body);
        });
    });
};

model.js

// Pulls Mongoose dependency for creating schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Defines how user data is stored in the database
var UserSchema = new Schema({
    username        :   {type: String, required: true},
    gender          :   {type: String, required: true},
    age             :   {type: Number, required: true},
    favlang         :   {type: String, required: true},
    location        :   {type: [Number], required: true}, //[Long, Lat]
    htmlverified    :   String,
    created_at      :   {type: Date, default: Date.now},
    updated_at      :   {type: Date, default: Date.now}
});

// Sets the created_at parameter equal to the current time
UserSchema.pre('save', function(next){
    now = new Date();
    this.updated_at = now;
    if(!this.created_at){
        this.created_at = now
    }
    next();
});

// Indexes this schema in 2dsphere format
UserSchema.index({location: '2dsphere'});

// Exports the UserSchema for use elsewhere
module.exports = mongoose.model('scotch-user', UserSchema);

server.js

// Dependencies
// -----------------------------------------------------
var express         = require('express');
var mongoose        = require('mongoose');
var port            = process.env.PORT || 3000;
var morgan          = require('morgan');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var app             = express();

// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect("mongodb://localhost/MeanMapApp");

// Logging and Parsing
app.use(express.static(__dirname + '/public'));                 
app.use('/bower_components',  express.static(__dirname + '/bower_components')); 
app.use(morgan('dev'));                                         
app.use(bodyParser.json());                                     
app.use(bodyParser.urlencoded({extended: true}));            
app.use(bodyParser.text());                                    
app.use(bodyParser.json({ type: 'application/vnd.api+json'}));  
app.use(methodOverride());

// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);

// Listen
// -------------------------------------------------------
app.listen(port);
console.log('App listening on port ' + port);

Answer №1

It seems like the mistake might be right here.

Instead of using:

module.exports = mongoose.model('scotch-user', UserSchema);

Consider using:

module.exports = mongoose.model('User', UserSchema);

Additionally, explore utilizing Express.js for handling your routes. When testing with Postman, make sure to input all the "required" fields for your MongoDB Schema.

Answer №2

I just implemented your code and everything is working smoothly!
Make sure to double-check the methods and routes in postman for accuracy.
Quick tip: Mongoose automatically handles schemas, so there's no need to export them.

You can easily follow these steps

index.js

// Dependencies
// -----------------------------------------------------
var express         = require('express');
var mongoose        = require('mongoose');
var port            = process.env.PORT || 3000;
var morgan          = require('morgan');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var app             = express();

// Load all models
require('./app/model');


// Express Configuration

model.js

// do not include module.exports at the end 
mongoose.model('User', UserSchema);

routes.js

// Dependencies
var mongoose        = require('mongoose');
var User            = mongoose.model('User');

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

Merge two separate Vue applications into one cohesive application

I have developed two separate Vue apps independently from each other. User Interface Admin Interface Each app has its own routes, store, configs, etc. I came across this helpful comment here which discusses treating each app as a component within a mai ...

The HTML attribute "hasbox" specifies the presence of a box within the element

I am currently working on resolving some rendering issues specifically in IE9 and have encountered a tag attribute that I am not familiar with - hasbox. Upon further investigation, it seems like IE is injecting this attribute at runtime as it does not app ...

JavaScript => Compare elements in an array based on their respective dates

I have an array consisting of more than 50 objects. This array is created by concatenating two arrays together. Each object in this array contains a 'date' key with the date string formatted as: `"2017-03-31T11:30:00.000Z"` Additionally, there ...

A guide on achieving a dynamic color transition in Highcharts using data values

I am currently working on plotting a graph using high charts and I would like to change the color based on the flag values. I attempted this, however, only the points are changing based on the flag values and the line is not being colored accordingly. Be ...

Check out this stylish Twitter-inspired SVG text counter created with a combination of CSS and jQuery! See it in action here: https://jsfiddle.net/moss24

Looking to develop a text counter similar to Twitter that increases the width in green color up to 75%, then switches to yellow until 98%, and finally turns red if the input value is greater than or equal to 400. It should also add a "highlight" class when ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

The functionality of the jQuery click event is not functioning properly

I encountered a strange issue where the code below works perfectly fine when directly pasted into the browser (chrome console). However, it does not work when executed from my source file. <script type="text/javascript" > $(".test").click( ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

Enhance your SVG progress circle by simply selecting checkboxes

I have a unique system with 5 checkboxes that act as a To-Do list. When I click on each checkbox, the circle's diameter should progressively fill up in increments of 1/5 until all 5 checkboxes are completed. The order in which the checkboxes are click ...

Error: Failed to load chunk XY - Production environment experiencing intermittent fatal errors

Our ecommerce platform is already in production and we are facing a strange ChunkLoadError. This error occurs randomly and is not reproducible. When attempting to open the failed file, it is present and can be loaded normally. If a user encounters this er ...

Nuxt - issue with updating window innerwidth getter

The class based components in our project utilize a getter to retrieve the window innerWidth. However, I've noticed that the value is only set once and doesn't update if the window width changes. get viewPortWidth() { if (process.client) { ...

Dealing With HttpClient and Asynchronous Functionality in Angular

I've been pondering this issue all day. I have a button that should withdraw a student from a class, which is straightforward. However, it should also check the database for a waiting list for that class and enroll the next person if there is any. In ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

Optimizing MongoDB connection handling in a Serverless (AWS Lambda) application: Best practices for caching and reusing

I am currently developing a Serverless application utilizing NodeJS and integrating with MongoDB. I have observed that multiple connections are being established when processing a request. To address this issue, I implemented a caching mechanism, but unfor ...

Unlock the power of traccar API to effortlessly obtain real-time location updates without the need for setIntervals or sockets

When working with node.js and express, I am facing issues with getting live location data using WebSocket. Occasionally, I encounter errors or disconnections from the service. I attempted to use the setInterval function, but having the server call every ...

Is it possible to combine multiple filter examples together?

Could you please provide some examples or references related to the next task: var planets = [{ residents: [{ name: 'Mars' }, { name: 'Jupiter' }, ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

The jQuery .ajax() function encountered a 405 error stating "Method Not Allowed" when attempting a cross

Despite searching extensively on SO, I am unable to pinpoint the issue in my code. To avoid using JSONP, I am implementing CORS. I understand that this is a preflighted request and believe I have included the correct headers. The problem lies in the web ...

serializeArray encounters difficulty in locating certain input elements

I've created this HTML layout: <div class="col-md-12"> <div class="form-group"> <label>Mini description (displaying the latest added destinations and meta description)</label> <textarea class="for ...