Use multiple atomic operations on same field

I have a field in my Post collection called reactions, which is an array of JSONs. Whenever I want to add a new object to that array, everything works as it should! There are times though that I want to replace an object inside that array with a new one, doing this;

const newReaction = { userId: currentUserId, isDownvote: false };

post.remove("reactions", post.get("reactions")[indexOfReactionToRemove]);
post.add("reactions", newReaction);

The thing is that as soon as it gets to the add call, the process hangs… any idea why?

I don’t know if it is related, but I do not recommend using arrays to store lists with more than 20 items on average. It can cause serious performance problems. I’d use relations or joint classes instead.

1 Like

I appreciate the comment! Could you explain why 20? It actually is right now a join-class and I thought it would be much of an improvement not to have to query a collection every time the user requests content!

EDIT; Every post has 20 likes on average, although there are others with 100 or more… not many of the daily feed though!

20 is an empirical number based on what I’ve seen. If you have few objects with more than 100 items in an array field, maybe some of them with 500 or 1000, it can start causing problems in the whole database. I’d also not use arrays for lists that can grow over time. Example of something that fits well on arrays: post’s categories, tags. Example of something that can cause problems: post’s followers, likes, comments.

1 Like

Thanks for responding! Could you clarify what you mean by “it can start causing problems in the whole database”? What kind of problems?

There are many articles out there talking about issues with big arrays and objects on MongoDB. Long story short it makes your collection to be fragmented on your storage. Since it is fragmented, any write operation on this collection (not only related to the array field, but actually any field) can start taking a long time. Since write operations take lock of the database, all other concurrent operations can start delaying as well. I’ve seen this happening myself many times.

1 Like

Thank you very much for your detailed explanation!!

1 Like