0

嗨,我目前是 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)

但我已经正确定义了赢,这似乎是什么问题?

4

2 回答 2

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

我希望您能理解您的问题并更新您的用户收藏。

于 2013-10-19T20:08:09.713 回答
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是 null
  • findOneAndUpdate仅供参考,您可以通过单个操作同时进行查找和更新
于 2013-09-23T23:52:21.900 回答