我在nodejs/mongodb上的更新函数上做错了什么

What am I doing wrong on my update function on nodejs/mongodb?

本文关键字:函数 错了 什么 更新 nodejs mongodb 我在      更新时间:2023-09-26

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

但我已经正确定义了胜利,似乎有什么问题?

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操作同时进行查找和更新
  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");
   }
 });

我希望您能了解您的问题并可以更新您的用户集合。