简体   繁体   中英

Cannot find module mongoose

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.

只需使用npm install mongoose而不是全局执行,即 npm install mongoose -g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM