问题是.. 有时它会在屏幕上显示错误的用户(有人获得了另一个人的会话)。但这几乎不会发生,我认为只有在有一些并发时才会发生。
如果此代码中的任何内容可以使这种行为发生,请提出建议。
app.js——这个文件有一个模式和模型和路由组件的启动
var userSchema = mongoose.Schema({
"_id": mongoose.Schema.Types.ObjectId,
"name": String,
"username":String,
"etc":String
});
userMongooseModel = mongoose.model('users',userSchema);
var sessionSchema = mongoose.Schema({
"userID": mongoose.Schema.Types.ObjectId,
"sessionID": String,
"expire":Number
});
sessionMongooseModel = mongoose.model('sessions',sessionSchema);
var UserModel = require(basePath+'/models/UserModel.js').UserModel;
userModel = new UserModel();
var user = require(basePath+'/routes/user');
routes/user.js——这个文件是关于每条路由的详细信息。
exports.editProfilePage = function(req,res){
var httpRes = res;
userModel.checkSession(req.cookies.session,function(res){
if(res.status=='success' && res.type=='photographer')
{
userModel.getByID(res.userID,{},function(resp){
httpRes.render(basePath+'/views/photographer-edit.html',{currentUser:res.user,user:resp.user,etc:'etc'});
});
}
else
{
//if not login or state != 0
httpRes.redirect(baseURL+'/photographerRedirect');
}
});
}
usermodel.js - 这个文件是从数据库中检索数据
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var request = require('request');
UserModel.prototype.checkSession = function(sessionID,callback){
sessionMongooseModel.findOne({sessionID:sessionID},function (err, user) {
if(err)
{
callback({status:'fail',errorMsg:'notFound'});
return;
}
if(user==null)
{
callback({status:'fail',errorMsg:'notFound'});
}
else
{
if(user.expire > Date.now())
{
userMongooseModel.findOne({_id:user.userID},{studioName:1,state:1,etc:1},function (err, user) {
if(err || user==null)
{
callback({status:'fail',errorMsg:'notFound'});
return;
}
if(user.type=='photographer' && user.state==0)
{
callback({status:'fail',errorMsg:'wrongUserState',userID:user._id,user:user,etc:1});
}
else
callback({status:'success',userID:user._id,user:user,type:user.type,etc:1});
});
}
else
{
callback({status:'fail',errorMsg:'notFound'});
}
}
});
}
UserModel.prototype.getByIDs = function(userIDs,options,callback){
userMongooseModel.find({_id:{$in:userIDs}},options,function (err, users) {
if(err){
callback({status:'fail',errorMsg:'UserModel.find'});
return;
}
callback({status:'success',users:users});
});
}
非常感谢 !