Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 架构中表示用户的方法的“TypeError:undefined不是函数”_Node.js_Mongodb_Express_Runtime Error - Fatal编程技术网

Node.js 架构中表示用户的方法的“TypeError:undefined不是函数”

Node.js 架构中表示用户的方法的“TypeError:undefined不是函数”,node.js,mongodb,express,runtime-error,Node.js,Mongodb,Express,Runtime Error,我在玩《Mean Machine》一书中的练习,创建一个API,验证一个用户并给出一个令牌。我在comparePassword上得到一个“TypeError:undefined不是函数”。我做错了什么 这是我的错误 server.js:69 var validPassword = user.comparePassword(req.body.password); ^ TypeError: undefined is not a f

我在玩《Mean Machine》一书中的练习,创建一个API,验证一个用户并给出一个令牌。我在comparePassword上得到一个“TypeError:undefined不是函数”。我做错了什么

这是我的错误

  server.js:69
  var validPassword = user.comparePassword(req.body.password);
                               ^
TypeError: undefined is not a function
下面是导致问题的代码:

 // more routes for our API will happen here
apiRouter.post('/authenticate', function(req, res){
    // find the user
    // select the name username explicitly
    User.findOne({
        username: req.body.username
    }).select('name username password').exec(function(err, user){

        if(err) throw err;

        // no user with that username was found
        if (!user){
            res.json({ 
                success: false, 
                message: 'Authentication failed. User not found'
            });

        }else if (user) {
            // check if password matches
            var validPassword = user.comparePassword(req.body.password);
            if(!validPassword){
                res.json({ 
                    success: false, 
                    message: 'Authentication failed. wrong password'
                });
            } else {

            // if user is found and password is right
            // create a token   
            var token = jwt.sign({
                name: user.name,
                username: user.username
            }, superSecret, {
                expiresInMinutes: 1440 // expires after 24 hours
            });

            // return the information including token as JSON
            res.json({
                success: true,
                message: 'enjoy your token!',
                token: token
            }); 
        }
      } 

    });
});
以下是server.js文件其余部分的上下文:

// Base Setup
// ======================================

// CALL THE PACKAGES
var express     = require('express'); // call express
var app         = express(); // define our app using express
var bodyParser  = require('body-parser'); // get body-parser
var morgan      = require('morgan'); // used to see requests
var mongoose    = require('mongoose'); // for working w/ our database
var User        = require('./app/models/user');
var port        = process.env.PORT || 8080; // Set the port for our app
var jwt = require('jsonwebtoken');

// super secret for creating tokens
var superSecret = 'rockabyezebra';

//APP CONFIGURATION 
// Use body-parser so we can grab information from post requests
app.use(bodyParser.urlencoded({extended: true }));
app.use(bodyParser.json());

// configure our app to handle CORS requests
app.use(function(req, res, next){
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET', 'POST');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, \ Authorization');
    next();
});


// log all requests to the console
app.use(morgan('dev'));

// connect to our database (hosted on mongolab.com)
mongoose.connect('mongodb://blah:blahblah@ds031852.mongolab.com:31852/app42');

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


// basic route for the homepage
app.get('/', function(req, res){
    res.send('Welcome to the home page');
});

// get an instance of the express router
var apiRouter = express.Router();

// more routes for our API will happen here
apiRouter.post('/authenticate', function(req, res){
    // find the user
    // select the name username explicitly
    User.findOne({
        username: req.body.username
    }).select('name username password').exec(function(err, user){

        if(err) throw err;

        // no user with that username was found
        if (!user){
            res.json({ 
                success: false, 
                message: 'Authentication failed. User not found'
            });

        }else if (user) {
            // check if password matches
            var validPassword = user.comparePassword(req.body.password);
            if(!validPassword){
                res.json({ 
                    success: false, 
                    message: 'Authentication failed. wrong password'
                });
            } else {

            // if user is found and password is right
            // create a token   
            var token = jwt.sign({
                name: user.name,
                username: user.username
            }, superSecret, {
                expiresInMinutes: 1440 // expires after 24 hours
            });

            // return the information including token as JSON
            res.json({
                success: true,
                message: 'enjoy your token!',
                token: token
            }); 
        }
      } 

    });
});


// middleware to use for all requests
apiRouter.use(function(req, res, next){
    // do logging   
    console.log('Somebody just visited our app');
    // we'll add more to the middleware in Chapter 10
    // this is where we will authenticate users
    next();  // make sure we go to the next routes and don't stop here
});





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



// on routes that end in /users
// ---------------------------------------------------
apiRouter.route('/users')

    // create a user (accessed at POST http://localhost:8080/users)
    .post(function(req, res){

        // create a new instance of the user model
        var user = new User();

        // set the users information (comes from the request)
        user.name = req.body.name;
        user.username = req.body.username;
        user.password = req.body.password;

        // save the user and check for errors
        user.save(function (err) {
            if (err){
            // duplicate entry  
            if (err.code ==11000)
                return res.json({ success: false, message: 'A user with that username already exists. '});
            else
                return res.send(err);
            }
            res.json ({ message: 'User created'});
        });
    })

    // get all the users (accessed at GET http://localhost:8080/api/users)
    .get(function(req,res) {
        User.find(function(err, users) {
            if (err) return res.send(err);

            // return the users
            res.json(users);
        });
    });

// on routes that end in /users/:user_id
// ----------------------------------------------------
apiRouter.route('/users/:user_id')

    // get the user with that id
    .get(function(req, res) {
        User.findById(req.params.user_id, function(err, user) {
            if (err) return res.send(err);

            // return that user
            res.json(user);
        });
    })

// update the user with this id
    .put(function(req, res){
        User.findById(req.params.user_id, function(err, user) {
            if (err) return res.send(err);

            // set the new user information if it exists in the request
            if(req.body.name) user.name = req.body.name;
            if(req.body.username) user.username = req.body.username;
            if(req.body.password) user.password = req.body.password;

            // save the user
            user.save(function(err){
                if (err) return res.send(err);

            // return a message
            res.json({ message: 'user updated'});   
            });
        });
    })  

    .delete(function(req, res){
        User.remove({
            _id: req.params.user_id
            }, function(err, user) {
                if (err) res.send(err);

            res.json({ message: 'Successfully deleted'});
        });
    });




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

// START THE SERVER
// ================================
app.listen(port);
console.log('rockin\' on port ' + port + ' y\'all');

我假设您正在使用mongoose模块获取数据。看起来您从来没有在用户模型来自的UserSchema中定义过comparePassword方法。您可以像这样在模式中定义方法。文件:


非常感谢,非常有帮助,你说得对。在我定义方法的时候,我犯了一个错误:它现在起作用了。谁知道为什么有人觉得有必要“投票否决”我最初的问题:@AgentZebra:你发布了大量代码,但没有生成简单的测试用例。在将来,一个简单的测试用例是解决问题的第一件事。如果仍然找不到,请使用testcase创建一个stackoverflow问题。
var AnimalSchema = new Schema({
  name: String,
  type: String
});

AnimalSchema.methods.findSimilarType = function findSimilarType(cb) {
  return this.model('Animal').find({
    type: this.type
  }, cb);
};
// Now when we have an instance of Animal we can call our // findSimilarType method and find all animals with a matching type.

var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({
  name: 'Rover',
  type: 'dog'
});

dog.findSimilarType(function(err, dogs) {
  if (err) return ...
  dogs.forEach(..);
})