[Mongoose]如何在app.js中使用两个不同的模式两次使用相同的模型

时间:2014-07-30 14:24:29

标签: node.js express mongoose passport.js

我正在尝试访问相同的数据库/模型以进行注册和登录功能但每次我尝试运行我的节点应用程序时都会收到此错误消息“无法覆盖'用户'模型一旦编译”这是我的代码:

//sign-up schema
var Schema = new mongoose.Schema({
  _id: String,
  name: String,
  username: String,
  password: String, 
  age: Number
});

var user = mongoose.model('users', Schema);

//sign-up login
app.post('/new', function(req, res) {
new user({
    _id: req.body.email,
    name: req.body.name,
    username: req.body.username,
    password: req.body.password,
    age: req.body.age

}).save(function(err, doc){
    if(err) res.json(err);
    else res.send('Successfully Signed up');
  });
});

//login schema
var Schema = mongoose.Schema;
var UserDetail = new Schema({
   username: String,
   password: String
}, {
   collection: 'users'
});
var UserDetails = mongoose.model('users', UserDetail);

//login logic
passport.use(new LocalStrategy(function(username, password, done) {
process.nextTick(function() {
UserDetails.findOne({
  'username': username, 
}, function(err, user) {
  if (err) {
    return done(err);
  }

  if (!user) {
    return done(null, false);
  }

  if (user.password != password) {
    return done(null, false);
  }

  return done(null, user);
  });
});
}));

1 个答案:

答案 0 :(得分:0)

您仍然可以使用相同的架构进行查找。

<强>模式

var Schema = new mongoose.Schema({
    _id: String,
    name: String,
    username: String,
    password: String,
    age: Number
});

var user = mongoose.model('users', Schema);

<强>注册

app.post('/new', function(req, res) {
    new user({
        _id: req.body.email,
        name: req.body.name,
        username: req.body.username,
        password: req.body.password,
        age: req.body.age
    }).save(function(err, doc) {
        if (err) res.json(err);
        else res.send('Successfully Signed up');
    });
});

<强>登录

passport.use(new LocalStrategy(function(username, password, done) {
    process.nextTick(function() {
        user.findOne({
            'username': username
        }, function(err, user) {
            if (err) {
                return done(err);
            }

            if (!user) {
                return done(null, false);
            }

            if (user.password !== password) { 
                return done(null, false); 
            }

            return done(null, user);
        });
    });
}));

如果您不想在回复中返回密码,只需添加

即可
delete user.password;
在回调之前