2016-10-31 2 views
0

Я хочу, чтобы пользователи моего приложения увеличивали value только один раз. Следующий код не работает, потому что update в мангусте асинхронен. Моя проверка if(user.valueIncremented) не подходит для следующих последовательных запросов к этому api, потому что valueIncremented не обновляется в этой точке, но будет находиться в следующем цикле событий. Итак, что мне делать, добрые господа?Атомное обновление в Mongoose

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

Где вы настройки req.user.valueIncremented? И как это точно проваливается? –

ответ

0

Здесь я добавил дополнительный запрос к базе данных. Теперь, когда я делаю два или более consective вызова этого api, value увеличивается только один раз.

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 }) 
 
})

Смежные вопросы