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
?それはどうやって失敗するのだろう? –