findOneAndUpdate使用MEAN堆栈失败

时间:2017-06-20 05:23:39

标签: javascript node.js mongoose mean-stack

这是我的 layout.handlebars

上的代码
 $(document).ready(function(){
        var socket = io();

        //     //understand button
        $(".understandbtn").click(function(){
            //reset the timer every 3 second of interval
            $('.actionBtnFloat').css('z-index','0');

            //e_money
             var deduct = 100;
             var newMoney = {{user.e_money}} - deduct;

  // send a message to the server that the e-money value has changed
 //get the current user
             socket.emit('update e-money',getUserName(), newMoney);

             // console.log("Emitting the data to the server side - emoney" + getUserName() + "with the name money of :" + newMoney);
            //end 

            clearTimeout(interval);
            //send the data to the server
            socket.emit('chat message', getUser());
            var interval = setTimeout(function(){
                $('.'+getUser()).fadeIn();
            },5000);
        });

             socket.on('update e-money response', function (data) {
             alert("Your money is: "+ data.newMoney);
             console.log("Your money is:" + data.newMoney);
             });

            socket.on('update e-money error', function (err,data) {
                if(err) throw err;
            // alert("Could not update your money: "+ data.error);
            // console.log("Could not update your money"+ data.error);
                alert("Sucessfully updated  your money");
                console.log("Sucessfully updated your money");
            });

在我的服务器上,这是我如何更新我的记录,但它无法正常工作 是因为错误吗?

//emoney
socket.on('update e-money', function (data) {
var userName = data.username;
var newMoney = data.newMoney;
var query = {username: userName};

// update the entry on the database
User.findOneAndUpdate(query, { e_money: newMoney }, { upsert: true, new: true }, function (err, doc) {
if (err) {
  io.emit('update e-money error', { error: err });
  console.log(err);
} else {
    io.emit('update e-money response', { e_money: newMoney });
    console.log(newMoney);
}
});
});

//end emoney

现在它说无法更新我的记录 是因为我不使用_id代替吗?

这是我的错误

消息:'转换为数字失败,值为#34;未定义"在路径" e_money"',   名称:' CastError',   stringValue:'" undefined"',   善良:'数字',   值:未定义,   路径:' e_money',   理由:未定义}

1 个答案:

答案 0 :(得分:0)

通过这样做实现了我想要的

User.findOneAndUpdate({"username":userName}, 
{"$set":{"e_money": newMoney }}, { upsert: true, returnOriginal:false }, 
function (err, doc) {