我现在尝试创建服务器应该可以注册用户。 但是,尝试使用/ reg注册时服务器没有反应。 当我创建一个新的.get时它确实会响应,所以服务器本身正在工作。
我还不清楚如何正确格式化网址。
app.post('/reg/:uname/:teamid', function(req, res){
var username = req.params.uname;
var teamidpar = req.params.teamid;
UserSchema.pre('save', function (next) {
this1 = this;
UserModel.find({uname : this1.username}, function(err, docs) {
if (!docs.length) {
//Username already exists
} else {
var loginid = randomstring.generate();
var newUser = User({
uname : username,
teamid : teamidpar,
totalscore : 0,
lastopponement : null,
gamescore : 0,
});
User.save(function (err, User, next) {
if (err) {return console.error(err);}
else
{console.log(timestamp+':'+'User created:'+newUser.uname+':'+newUser.login);}
res.json({login : loginid});
});
}
});
});
});
答案 0 :(得分:0)
我不知道为什么我之前没有看到这个,但你在开头使用UserSchema.pre
,但这只是一个定义,不会立即执行。只有当您在文档上实际执行save
时才会触发此功能。
在正确的编辑版本下面。
app.post('/reg/:uname/:teamid', function(req, res) {
var username = req.params.uname;
var teamidpar = req.params.teamid;
// If you are just checking if something exist, then try count
// as that has minimal impact on the server
UserModel.count({uname : username}, function(err, count) {
if (count > 0) {
// Username already exists, but always output something as we
// don't want the client to wait forever
return res.send(500);
}
var loginid = randomstring.generate();
// You'll need a new instance of UserModel to define a new document
var newUser = new UserModel({
uname : username,
teamid : teamidpar,
totalscore : 0,
lastopponement : null,
gamescore : 0,
});
// Save the document by calling the save method on the document
// itself
newUser.save(function (err) {
if (err) {
console.error(err);
// You'll want to output some stuff, otherwise the client keeps on waiting
return res.send(500);
}
console.log(timestamp + ': User created:' + username + ':' + loginid);
res.json({login : loginid});
});
});
});