0
votes

I am trying to make my backend work with MongoDB ATLAS. I'm using express, mongoose and node.js for my tests and when I am trying to test my API routes (in this case to add a user)

The code I have is the following:

users.js

const router = require('express').Router();
const { Router } = require('express');
let User = require('../models/user.model');

router.route('/').get((req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {
  const username = req.body.username;

  const newUser = new User({username});

  newUser.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Error: ' + err));
});


module.exports = router

user.model.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
}, {
  timestamps: true,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

When I am testing this with postman via a POST I get the following error: I am getting the following error: TypeError: User is not a constructor

The post is done to http over port 5000 with raw json body as "username": "blahblahblah"

Can you help with this maybe?

1
Try: User.create({username}) should not need to do a .save then. - Mellet
with newUser.create({username}) I get the same result in the POST. - Shando
show me the result of console.log(req.body) - Mohammad Yaser Ahmadi
It's { username: 'quincy' } This is what I am sending in the POST as JSON - Shando
no, write console.log(req.body) in add route, and show me the result maybe the req.body is null - Mohammad Yaser Ahmadi

1 Answers

0
votes

I am not sure what happened but today I cut and pasted back all the code and the API started to work just fine. Now I can add users without any problems.

Could be a glitch but not sure at this point.