我想在我的expressJS API 中具有登录/注册功能。 所以现在我只是将密码和电子邮件插入我的数据库,我希望此功能首先检查具有此电子邮件的用户是否已在数据库中 - 如果是,则发送用户已记录的响应。 如果没有,只需将其插入数据库即可。 这里可以处理一些错误吗?
我已经有了:
exports.login = function(req, res){
var email = req.body.email;
var pwd = req.body.pass;
db.collection('users', function(err, collection) {
collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
res.send("OK");
});
});
};\
并且不知道接下来会发生什么。
最佳答案
您可以首先尝试在数据库中查找该用户。假设电子邮件是唯一的;
exports.login = function(req, res){
var email = req.body.email;
var pwd = req.body.pass;
db.collection('users', function(err, collection) {
if (err) return res.send(500, err);
collection.findOne({login:email}, function(err, user) {
// we found a user so respond back accordingly
if (user) return res.send('user logged in');
collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
if (err) return res.send(500, err);
res.send("OK");
});
});
});
};
处理错误时,请注意 res.send
调用之前的 return
。
关于javascript - ExpressJS + MongoDB - 登录/注册方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760320/