1

I am creating a simple crud API in nodeJS, express and mongoDB. I finished it and after testing, it was working just fine. But then I tried to play around with it and decided to store the password hash instead of the actual password. For this purpose, I used bcrypt npm package. More info on the package can be found here. But as soon I implemented it, I started having this issue with mongoose. I have tried everything mentioned here

The error I get is as follows: error Screenshot

My server.js file is:

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express')        // call express
var app        = express()                 // define our app using express
var bodyParser = require('body-parser')
var bcrypt = require('bcrypt')

const saltRounds = 10

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())

var port = process.env.PORT || 8080        // set our port

//connecting to the database
var mongoose   = require('mongoose')
mongoose.connect('mongodb://<username>:<password>@ds119533.mlab.com:19533/dbname')
var User     = require('./app/models/user')

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router()              // get an instance of the express Router

router.use( (req, res, next) => {
    console.log('Something is happening...')
    next()
} )

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', (req, res) => {
    res.json({ message: 'hooray! welcome to our api!' })   
})

// more routes for our API will happen here

// create a user (accessed at POST http://localhost:8080/api/users)
router.route('/users')
    .post( (req, res) => {
        var user = new User()        //create a new user

        user.name = req.body.name    //setting user properies
        user.email = req.body.email
        bcrypt.genSalt(saltRounds, (err, salt) => {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
            user.password = hash 
            })       
        })

        //save the user
        user.save( (err) => {
            if (err)
                console.error('Something went wrong')

            res.json({message: 'User created...!'})
        }) 
    })

    .get( (req, res) => {
        User.find( (err, users) => {
            if(err){
                console.error('Could not get the users list...')
                res.send(err)
            }

            res.json(users)
        })
    })

router.route('/users/:user_id')

    // get the user with this id (accessed at PUT http://localhost:8080/api/users/:user_id)
    .get( (req, res) => {
        User.findById(req.params.user_id, (err, user) => {
            if(err){
                console.error('Could not get the user...')
                res.send(err)
            }

            res.json(user)
        })
    })

    // update the user with this id (accessed at PUT http://localhost:8080/api/users/:user_id)
    .put( (req, res) => {
        User.findById(req.params.user_id, (err, user) => {
            if(err){
                console.error('Could not get the user with this id...')
                res.send(err)
            }

            user.name = req.body.name
            user.email = req.body.email
            bcrypt.genSalt(saltRounds, (err, salt) => {
                bcrypt.hash(req.body.password, salt, (err, hash) => {
                user.password = hash 
                })
            })

            user.save( (err) => {
                if(err){
                console.error('Could not update the user...')
                res.send(err)
            }
                res.json({ message: 'User updated' })
            })

        })
    })

    // delete the user with this id (accessed at DELETE http://localhost:8080/api/users/:user_id)
    .delete( (req, res) => {
        User.remove({
            _id: req.params.user_id
        }, (err, user) => {
            if(err){
                console.error('Could not delete the user...')
                res.send(err)
            }

            res.json({ message: 'User deleted successfully...' })
        })
    })

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router)

// START THE SERVER
// =============================================================================
app.listen(port)
console.log('Magic happens on port ' + port)

My package.json file is:

{
  "name": "crud",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^1.0.2",
    "body-parser": "^1.17.2",
    "bson": "^1.0.4",
    "express": "^4.15.3",
    "mongoose": "~3.6.13",
    "password-hash": "^1.2.2"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

Whereas my mongoose schema file is:

var mongoose = require('mongoose')
var schema = mongoose.Schema

var userSchema = new schema({
    name: String,
    password: String,
    email: String
})

module.exports = mongoose.model('User', userSchema)

Any help would be appreciated.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Farhat Nawaz
  • 202
  • 5
  • 20
  • 1
    A simple `npm list` at any time will give you a quick overview of what is actually installed. I would suggest that in your "playing around" you actually managed to wipe some installed modules. Also Mongoose 3.x is getting a little old. So you are either being extremely conservative or basing your code of a "very old blog post". Somehow the latter seems more likely. – Neil Lunn Jul 24 '17 at 12:05
  • Also please don't use screenhots or merely "link" to other answers etc etc. If you "tried something" then "show what you actually did". If we just presumed you followed instructions posted elsewhere then you would not have a problem at all, and would not need to post the question. – Neil Lunn Jul 24 '17 at 12:07
  • @NeilLunn I updated mongoose and the issue resolved. Looks like bcrypt doesn't work with older versions of mongoose. thanks man – Farhat Nawaz Jul 24 '17 at 12:10
  • Actually it would be more likely that "mongoose left the building". Like I said, links to other questions does not really faithfully represent that you actually followed the steps. But forcing an upgrade does ensure something gets installed. – Neil Lunn Jul 24 '17 at 12:12

1 Answers1

2

just use npm install mongoose instead of doing it globally i.e npm install mongoose -g

Alish Madhukar
  • 391
  • 1
  • 5
  • 18