MongoDB arrays vs objects

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?

Answers


You don't have to use a for-loop if the colors are stored as an array. You can just use indexOf, as in:

if(user.colors.indexOf("yellow") != -1){
   //true case
}

That said, it really shouldn't matter either way whether you use an embedded document or array; it's not like one or the other is going to give a huge performance advantage.


Need Your Help

Check if size has been set with JavaScript in IE

javascript internet-explorer coding-style size

I was wondering if there was a way in JavaScript to check if the size of an element has previously been set? Even though this obviously wont work, this is kind of what I need to happen.

Spring Boot @Controller refuses to work with @Autowired

java spring spring-mvc spring-boot

I used this tutorial to build Spring Boot application. It appeared super easy at first glance but I ran into number of problems right away. When trying to access /hi or /thing tomcat 7 returns 404 ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.