2016-10-31 9 views
0

私のアプリのユーザーには、valueを1回だけ増やすことができます。 mongoose内のupdateは非同期であるため、次のコードは失敗します。 valueIncrementedはこの時点では更新されていませんが、次のイベントループ上にあるため、私のチェックif(user.valueIncremented)はこのAPIへの次回の連続リクエストで失敗します。だから、私は何をするのですか、良い先生ですか?ここでモンゴースの原子的更新

var Account = new Schema({ 
 
\t _id: Schema.Types.ObjectId, 
 
\t value: {type: Number, default: 0}, 
 
\t valueIncremented: {type: Boolean, default: false} 
 
}); 
 

 
router.post('/incrementValue', function(req, res, next) { 
 
\t var user = req.user; 
 
\t if(user.valueIncremented) { 
 
\t \t return next(); 
 
\t } 
 
\t else { 
 
\t \t incrementValue(); 
 
\t } 
 
\t function incrementValue(){ 
 
\t \t var condition = { 
 
\t \t \t _id: user._id; 
 
\t \t } 
 
\t \t var update = { 
 
\t \t \t $inc: { 
 
\t \t \t \t value: 1 
 
\t \t \t }, 
 
\t \t \t $set: { 
 
\t \t \t \t valueIncremented: true 
 
\t \t \t } 
 
\t \t } 
 
\t \t Account.update(condition, update).exec(); 
 
\t } 
 
}) \t

+0

?それはどうやって失敗するのだろう? –

答えて

0

私は、データベースに追加のクエリを追加しました。今、私はこのapiへの2つ以上のconsective呼び出しを行うと、valueが1回だけインクリメントされます。あなたがreq.user.valueIncrementedを設定している

router.post('/incrementValue', function(req, res, next) { 
 
\t var id = req.user._id; 
 
\t Account.findById(id).exec(function(err, user){ 
 
\t \t if(err) { 
 
\t \t \t return next(err); 
 
\t \t } 
 
\t \t if(user.valueIncremented) { 
 
\t \t \t return next(); 
 
\t \t } 
 
\t \t else { 
 
\t \t \t incrementValue(); 
 
\t \t } 
 
\t \t function incrementValue(){ 
 
\t \t \t var condition = { 
 
\t \t \t \t _id: id 
 
\t \t \t } 
 
\t \t \t var update = { 
 
\t \t \t \t $inc: { 
 
\t \t \t \t \t value: 1 
 
\t \t \t \t }, 
 
\t \t \t \t $set: { 
 
\t \t \t \t \t valueIncremented: true 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t \t Account.update(condition, update).exec(); 
 
\t \t } \t \t 
 
\t }) 
 
})

関連する問題