1

I am building a simple node.js app. I build my backend api for user registration. I am trying to test it with postman and i am having this error 'Illegal arguments: undefined, string'. What could be responsible for this?. Relevant codes are supplied below

User Schema

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

const UserSchema = new Schema({

    userName: {
        type: String,
        required: true,
        unique: true

    },
    firstName: {
        type: String,
    },
    lastName: {
        type: String,
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    dateOfRegistration: {
        type: Date,
        default: Date.now
       
    },
    dateOfBirth: {
        type: Date,
    },
     userCategory: {
        type: String,
        default: 'workingClass'
       
    }

})
module.exports = mongoose.model('users', UserSchema)


2
  • 1
    The first argument for mongoose.model is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus you should use module.exports = mongoose.model('User', UserSchema) Commented Apr 15, 2021 at 11:24
  • Kindly provide the controller action and probably a screenshot of the test to analyze Commented Apr 15, 2021 at 11:25

2 Answers 2

3

The problem has been solved. Postman was sending the request as in 'text' format instead of 'JSON' format and as such the backend couldn't make sense of data. Every worked fine when changed the settings on my Postman from 'text' to 'JSON'.

Sign up to request clarification or add additional context in comments.

Comments

0

controller

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const auth = require('../middleware/auth')
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
const UserModel = require('../models/User');


// @route   POST api/users, Register a users; access   Public

router.post('/', [
    check('userName', 'Please add user name').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check('password', 'Please enter a password with six or more characters').isLength({ min: 5 })
    ],
  async (req, res) => {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    
    const  { userName, firstName, lastName, email, password, dateOfBirth, dateOfRegistration, userCategory } = req.body;

    try {
        let user = await User.findOne( { email });

        if (user) {
            return res.status(400).json({ msg: 'User already exist'})
        }
        
        user = new User({
            userName,
            firstName,
            lastName,
            email,
            password,
            dateOfBirth,
            dateOfRegistration,
            userCategory
        });

        const salt = await bcrypt.genSalt(10);

        user.password = await bcrypt.hash(password, salt);

        await user.save();

        
        const payload = {
            user: {
                id: user.id
            } 
        }

      
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error')  
    }
   }
  );

module.exports = router;

server.js

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

// api require routes
const users = require('./routes/users');
// const auth = require('./routes/auth');
// const students = require('./routes/studentsSub');
// const workers = require('./routes/workersSub');


const app = express();

// database connection
const connectDB = async () => {
    try {
        await mongoose.connect('mongodb+srv://nawill:[email protected]/myFirstDatabase?retryWrites=true&w=majority', 
        {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false  
        });
        console.log('MongoDB Connected ...')
    } catch (err) {
        console.error(err.message);
        process.exit(1);
    }
};
connectDB();

//Middleware
app.use(express.json({ extended: false }));
// app.get('/', (req, res) => res.json ({ msg: 'Hello node project'}));


//Routes
app.use('/api/users', users );
// app.use('/api/auth', auth );
// app.use('/api/students', students );
// app.use('/api/workers', workers );


//Start Server
app.listen(3000, ()=> console.log("Server started on 3000"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.