Suppose I want to keep a list of items for each user (in MongoDB with Mongoose ODM in Node.js) and a later query to find out if the item belongs to the user. For example, I want to save all the favorite colors of each user, and then see if a particular color belongs to a specific user. It seems to me that it is better to store colors as an embedded object inside a user document, rather than an array in a user document. The reason is that it seems more efficient to check if a color exists in an object, since I can simply check if an object property exists:
if(user.colors.yellow){ //true case } else { //false case }
Compared to an array, where I have to iterate over the entire array to see if any color exists in the array:
for (var i = 0; i < user.colors.length; i++) { if(user.colors[i] === "yellow"){ //true case } else { //false case } }
However, from the many examples I've seen on the Internet, it seems that using arrays for this type of thing is pretty common. Am I missing something? What are the pros and cons and the best way to do this?
source share