您好我目前是nodejs和mongodb的新手,我想做的是创建一个函数来更新我的胜利,输掉,从我的用户手册中绘制记录。
我的架构:
UserSchema = new mongoose.Schema({
username:'string',
password:'string',
email:'string',
//Change Made
win:{ type: Number, default: 0 },
lose:{ type: Number, default: 0 },
draw:{ type: Number, default: 0 }
});
var db = mongoose.createConnection(app.get('MONGODB_CONN')),
User = db.model('users', UserSchema);
我的更新功能:
app.post('/user/updateScores',function(req, res){
try{
var query = req.body.username;
User.findOneAndUpdate(query, { win : req.body.win, lose : req.body.lose, draw : req.body.draw }, function (err,user){
if (err) res.json(err) ;
req.session.loggedIn = true;
res.redirect('/user/' + user.username);
});
}
catch(e){
console.log(e)
}
});
问题是当我尝试更新时,它会更新当前数据但是会转到空白页并抛出异常说:
ReferenceError: win is not defined
at eval (eval at <anonymous> (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\underscore\underscore.js:1176:16), <anonymous>:5:9)
at template (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\underscore\underscore.js:1184:21)
at Function.exports.underscore.render (C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:410:14)
at C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:106:23
at C:\Users\ryan-utb\Desktop\RockScissorsPaper\node_modules\consolidate\lib\consolidate.js:90:5
at fs.js:266:14
at Object.oncomplete (fs.js:107:15)
但我已经正确定义了胜利,似乎是什么问题?
答案 0 :(得分:0)
User.update(
{username:req.body.username},
{ win : req.body.win, lose : req.body.lose, draw : req.body.draw },
function (err, data) { //look - no argument name "user" - just "data"
//2 mistakes here that you should learn to never do
//1. Don't ignore the `err` argument
//2. Don't assume the query returns something. Check that data is not null.
console.log(data);
//The next line must be INSIDE this function in order to access "data"
res.redirect('/user/' + data.username);
});
//ACK don't try to access "data" (or "user") here. this is asynchronous code!
//this code executes EARLIER IN TIME than the User.update callback code
在您的代码段v2后更新
find
电话根本不匹配任何文件,因此user
为空findOneAndUpdate
操作同时进行查找和更新答案 1 :(得分:0)
User.update({
username: req.body.username
},{
$set: {
win : req.body.name,
loose : req.body.loose
}
}, function(err, result) {
if (err) {
console.log(err);
} else if (result === 0) {
console.log("user is not updated");
} else {
console.log("user is updated");
}
});
我希望您能够理解您的问题,并可以更新您的用户集。