2017-11-19 6 views
0

MongoDBの値を置き換えるポストリクエストを作成しようとしています。 ユーザーは、フォームに新しい値(ビットコイン)を入力します。フォームを送信すると、ポストの要求が開始されます。MongoDBのPOST要求による値の変更 - 角2

bitcoinChange(bitcoin){ 
    let headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    return this.http.post('http://localhost:3000/users/bitcoin', bitcoin, {headers: headers}) 
     .map(res => res.json()); 
    } 

ポスト要求は、提出された新しい値に、現在のビットコイン値(user.bitcoin)を変更し、ユーザー名で、現在のユーザーを検索します。

router.post('/bitcoin', (req, res, next) => { 
    const bitcoin = req.body.bitcoin; 

    User.getUserByUsername(username, (err, user) => { 
     if (err) throw err; 
     if (!user) { 
      return res.json({ success: false, msg: 'User not found.' }) 
     } 

     User.changeBitcoin(bitcoin, user.bitcoin,() => { 
      if (bitcoin = user.bitcoin) { 
       res.json({ success: false, msg: 'Failed to change Bitcoin amount.' }); 
      } else { 
       user.bitcoin = bitcoin; 
       res.json({ success: true, msg: 'Bitcoin amount changed!' }); 
      } 
     }); 
    }); 
}); 

changeBitcoin機能:

// Takes in what user types as the new bitcoin value, sets current value to candidateBitcoin 
module.exports.changeBitcoin = function(candidateBitcoin, callback){ 
    candidateBitcoin = User.bitcoin 
    User.save(callback); 
} 

が、これは、データベース内の値を変更するユーザーについて移動する正しい方法ですか?

答えて

0

いや

router.post('/bitcoin', (req, res, next) => { 
    const bitcoin = req.body.bitcoin; 
    User.update({ username }, { $set: { bitcoin } }) 
    .then(() => res.sendStatus(200)) 
    .catch(next); 
}); 
+0

興味深いは、必要がある唯一のものは変更することですか?それとも、投稿リクエスト後に私が持っていたものはすべて今は冗長ですか? – zahnzy

関連する問題