0

Hi I am currently new to nodejs and mongodb what I want to do is make a function to update my win,lose,draw record from my userschema.

My Schema:

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 }
});

My Function for updating:

//Update scores
app.post("/user/updateScores", function (req, res) {
    var user = new User({
        username:req.body.username,
        win:req.body.win,
        lose:req.body.lose,
        draw:req.body.draw  
    });

    Users.findOne({ username : req.params.username }, function(error, user) {
    if (error || !user) {
      res.send({ error: error });
    } else {
       user.update(function (err, user) {
       if (err) res.json(err)
        req.session.loggedIn = true;
        res.redirect('/user/' + user.username);
        });
    }
    });
});

The problem is when I try updating, when I try updating via my html file. It does not update anything and just stays the same (the values win,lose,draw the default value is 0 so when I logout and login again the values of the win,lose,draw record is still zero). I thoroughly checked if the problem was the html and javascript functions that I have made but this is not the case so I think that the problem is the update function I have made. Any of you guys have an idea where I went wrong? Thanks!

4

1 回答 1

0

假设您post从客户端正确调用,您需要注意变量和参数名称,因为现在的范围是您正在保存刚刚通过findOne.

您将 user 声明为post回调的变量,然后再次在findOne. 内部变量user将优先。

app.post("/user/updateScores", function (req, res) {
    var username = req.body.username;

    Users.findOne({ username : username }, function(error, user) {
        if (error || !user) {
          res.send({ error: error });          
        } else {
           // update the user object found using findOne
           user.win = req.body.win;
           user.lose = req.body.lose;
           user.draw = req.body.draw;
           // now update it in MongoDB
           user.update(function (err, user) {
               if (err) res.json(err) {
                   req.session.loggedIn = true;
               }
               res.redirect('/user/' + user.username);
           });
        }
    });
});
于 2013-09-22T18:08:13.863 回答