title: Having issues with checking if a user exists in db (MERN stack)
body: <hr />
  <p>Hi guys I'm doing my first full-stack MERN application and I've been trying everything to check if a user already exists (by either .exec() or using a callback function) in my database but I keep running into request errors (500 etc), code is below. I need your help geniuses!!!!</p>
  <hr />
  <p>'userModel.js'</p>
  <pre><code>const mongoose = require('mongoose');
  const Schema = mongoose.Schema;
  
  // new user model for mongo
  const UserSchema = new Schema({
    username: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true
    }
  }, 
  {
    collection: 'users'
  })
  
  module.exports = User = mongoose.model('user', UserSchema);
  </code></pre>
  <p>'users.js'</p>
  <pre><code>const express = require('express')
  const router = express.Router()
  const userModel = require('../models/userModel')
  const mongoose = require('mongoose')
  
  // POST users to db
  router.post('/', (req,res) =&gt;{
  
    // new instance of user model to be mutated
    const User = new userModel({
        // grabbing user register data and pushing to mongo
        username: req.body.username,
        password: req.body.password
    })
  
    // checking if user already exists
    User.findOne({username: req.body.username}, async function(err, user){
      if (err) {
        console.log(err);
      }
      if(user){
        console.log('user exists')
      }
      else{
        const newUser = await user.save()
        res.json(newUser)
        console.log(&quot;username: &quot;+ req.body.username + &quot;, password: &quot; + req.body.password)
        /*catch (err) {
          err =&gt; {res.json({message: err.message})}
        }*/
      }
  
    })
  })
  
  module.exports = router;
  </code></pre>
  <p>'app.js'</p>
  <pre><code>// Connect to database
  const db = require('./bin/mongoURI').mongoURI;
  
  mongoose
    .connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() =&gt; console.log('CONNECTED TO MONGODB'))
    .catch(err =&gt; console.log(err));
  </code></pre>