Cannot overwrite `users` model once compiled node js

I am getting this error while compiling my code

throw new mongoose.Error.OverwriteModelError(name);
      ^
OverwriteModelError: Cannot overwrite `users` model once compiled.

This is my Model/users.js file

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

//User Schema
const UserSchema = mongoose.Schema({
  name: {
    type:String
  },
  email: {
    type:String,
    required:true
  },
  username: {
    type:String,
    required:true
  },
  password: {
    type:String,
    required:true
  }
});

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

module.exports.getUserById = function(id,callback)
{
  User.findById(id,callback);
}

module.exports.getUserByUsername = function(username,callback){
  const query = {username: username}
  user.findOne(query,callback);
}
module.exports.addUser = function(newUser,callback){
  bcrypt.genSalt(10,(err,salt)=>{
    if(err)
    {
      throw err;
    }
    bcrypt.hash(newUser.password,salt,(err,hash)=>{
      newUser.password=hash;
      newUser.save(callback);
    });
  });
}

This is my route/users.js file

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
var Log = require('log')
  , log = new Log('info');

const User = require('../Model/users');
//const ap = express();

//Register router
router.post('/register',(req,res,next)=>{
  log.info('entering register');
  let newUser = new User({
    name:req.body.name,
    email:req.body.email,
    username:req.body.username,
    password:req.body.password
  });
  User.addUser(newUser,(err,user)=>{
    log.info("inside add user");
    if(err){
      log.error('error while registaring ' + err);
      res.json({success:false,msg:'failed to register user'});
    }
    else {
      res.json({sucess:true,msg:'user registered succefully'});
    }
  })
});
router.get('/authenticate',(req,res,next)=>{
  res.send("authenticated");
});
router.get('/profile',(req,res,next)=>{
  res.send('profile');
});
module.exports=router;

passport.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../model/users');
const config = require('../config/database');

module.exports = function(passport){
  let opts = {};
  opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts,(jwt_payload,done)=>{
    User.getUserById(jwt_payload._id,(err,user)=>{
      if(err)
      {
        return done(err,false);
      }
      if(user){
        return done(null,user);
      }
      else {
        return done(null,false);
      }
    })
  }));
}

I have tried suggestion from [Cannot overwrite model once compiled Mongoose but I am not able to understand what the problem is.

Answer

Update your require statements to be consistent in both the routes and passport file: const User = require('../model/users');. Case does matter!

It looks like you’re not using the correct mongoose terminology. Based on their documentation, this should be implemented roughly as follows.

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

//User Schema
const UserSchema = mongoose.Schema({
  name: {
    type:String
  },
  email: {
    type:String,
    required:true
  },
  username: {
    type:String,
    required:true
  },
  password: {
    type:String,
    required:true
  }
});

UserSchema.statics.getUserById = function(id,callback)
{
  return this.findById(id,callback);
};

UserSchema.statics.getUserByUsername = function(username,callback){
  const query = {username: username}
  return this.findOne(query,callback);
};
UserSchema.statics.addUser = function(newUser,callback){
  bcrypt.genSalt(10,(err,salt)=>{
    if(err)
    {
      throw err;
    }
    bcrypt.hash(newUser.password,salt,(err,hash)=>{
      newUser.password=hash;
      newUser.save(callback);
    });
  });
};

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

Leave a Reply

Your email address will not be published. Required fields are marked *