Reputation: 3018
I am building a real estate application using node and MongoDB
. I have two major models
I am now confused because I don't know if I should create a separate collection for cities and one for properties. Or I should put all the properties under it's city?
I am confused because I think when the application grow, large cities will be huge documents, which is a design decision should be done by the first.
Please let me know if you have a best practice way to handle this kind of situations.
Upvotes: 0
Views: 195
Reputation: 926
As every property has only one city, this is a one-to-many relationship. In this case you have many options:
Firstly, remember the 16 MB document size restriction per document. So, how big the "many" is. How many properties per city?
One-to-Few (just a few hundred): embedding the "few" (property) in "one" (city).
One-to-Many (no more than a couple of thousand): child-referencing. The ObjectIDs of the "many" (property) doc in an array in "one"(city) document.
One-to-Squillions: parent-referencing. Store the ObjectId of the "one" (city) in the "many" (property) document.
Secondly, if there’s an high ratio of reads to updates, you can considering denormalization. Paying the price of slower and complex updates in order to get more efficient queries.
A proposed solution: having only one collection (properties) and in their documents embed the city document. As probably, you are going to retrieve the properties by city, don't forget to create an index on the city field.
Recommending posts:
http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1 http://blog.mongodb.org/post/87892923503/6-rules-of-thumb-for-mongodb-schema-design-part-2 http://blog.mongodb.org/post/88473035333/6-rules-of-thumb-for-mongodb-schema-design-part-3
Upvotes: 1
Reputation: 1288
I assume the city center coordinates are not going to change very often. So embedding cities to properties is possible if the city documents are not very big and you need information abot them each time you read a property. On the other hand, you can put cities into a separate collection and link it from a property. Finally, you can embed most useful information about a city along with link to a property (mixed approach). Embedding a city to property will introduce some duplication but may increase read performance. To choose most appropriate option you need to understand what read/write requests the application will make most often.
Upvotes: 0