Reputation: 579
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?
Upvotes: 4
Views: 1272
Reputation: 103365
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()
.
Upvotes: 3