Lets say I want to maintain a list of items per user (in MongoDB with Mongoose ODM in Node.js environment) and later query to see if an item is owned by a user. For example, I want to store all of the favorite colors of each user, and later see if a specific color is owned by a specific user. It seems to me that it would be better to store the colors as an embedded object within the user document, rather than an array within the user document. The reason why is that it seems more efficient to check to see if a color exists in an object as I can just check to see if the object property exists:
if(user.colors.yellow){
//true case
} else {
//false case
}
Versus an array where I have to iterate through the entire array to see if the color exists somewhere in the array:
for (var i = 0; i < user.colors.length; i++) {
if(user.colors[i] === "yellow"){
//true case
} else {
//false case
}
}
However, from many of the examples I've seen online, it seems like using arrays for this type of thing is fairly prevalent. Am I missing something? What are the pros/cons, and best way to do this?