Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$inc only when $addToSet successful

Tags:

mongodb

meteor

In my project, I would like to increment my "number" field only if my $addToSet is successful. There are topics and there are users in each topics. When a user join a topic, I add his ID in the "users" array and I increment the number of users in the topic. Currently, my solution increment the field number even if the user is already in the users "array".

Topics.update(roomId ,{ $addToSet: { users: this.userId }, $inc: { number: 1 }});

I tried many things find in Google but I have always an error. How can I do this properly?

like image 310
user3415686 Avatar asked Sep 18 '25 18:09

user3415686


1 Answers

You could use two write operations for this process since that won't be possible within a single atomic update operation.

The first update operation increments the counter if the query satisfies the given criteria that the user does not exist and the next update operation then adds the user to the array using $addToSet:

var query = {
    _id: roomId,
    users: {"$ne": this.userId}
};
Topics.update(query, { $inc: { number: 1 } });
Topics.update(roomId, { $addToSet: { users: this.userId });

This is probably slightly less efficient because of the two db calls but if that's an issue that will potentially affect your application performance then you may write your own meteor wrapper for Mongo's findAndModify() by using Topics.rawCollection().

like image 89
chridam Avatar answered Sep 20 '25 07:09

chridam