MongooseJS保存后无法检索数据

时间:2015-01-24 17:52:16

标签: node.js mongoose passport.js passport-local

我有一个简单的ExpressJS应用程序,我正在尝试使用passport,passport-local和passport-local-mongoose为其添加用户身份验证,但是在我将用户的数据保存在db之后,mongoose无法检索它,尽管我可以通过mongo cli看到数据。

在主要的快递模块我有:

// Passport session setup.
var User = require("./models/user");
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

我的用户模型模块有:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');


// User Schema
var User = new Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true}
});


User.plugin(passportLocalMongoose);

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

在我的路线模块中,我使用以下代码创建一个用户:

router.post('/register', function(req, res) {

  var u = req.body.username;
  var p = req.body.password;

  console.log('Creating account for ' + u + ':' + p);
  // Store client on DB
  var usr = new User({ username: u, password: p });
  usr.save(function(err) {
    if(err) {
      console.log(err);
      return res.render('register', {title: 'Register', error: err.userMessage});
    } else {
      console.log('user: ' + usr.username + " saved.");
      passport.authenticate('local')(req, res, function () {
        return res.redirect('/dashboard');
      });
    }
  });

});

但是当我尝试使用passport.authenticate方法对用户进行身份验证时,mongoose无法在db上找到用户,正如我在mongoose日志中看到的那样:

Login request @  1422120637815
Mongoose: users.findOne({ username: 'e@e.com' }) { fields: undefined }  

但是在mongo cli,我可以看到数据:

> db.User.find()
{ "username" : "e@e.com", "password" : "123", "_id" : ObjectId("54c3d688fc71a4001db30612"), "__v" : 0 }

1 个答案:

答案 0 :(得分:0)

Mongoose正在寻找名为“users”的集合,但看起来您的数据存储在“用户”中。 model()的API是mongoose#model(name,[schema],[collection],[skipInit])。所以你可以通过添加第三个参数来强制收集名称,例如

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

EDIT1: 尝试使用mongoose-local

中的内置register()方法
router.post('/register', function(req, res) {

  var u = req.body.username;
  var p = req.body.password;

  console.log('Creating account for ' + u + ':' + p);
  // Store client on DB
    Account.register(new Account({ username: req.body.username }), req.body.password, function(err) {
     if(err) {
      console.log(err);
      return res.render('register', {title: 'Register', error: err.userMessage});
     } else {
       passport.authenticate('local')(req, res, function () {
         return res.redirect('/dashboard');
       });
     }
    });
});