Is a type property the correct way to store different data entities in CouchDB?
couchdb, data-modeling
Solution
Using `type` is convenient and fast when creating `views`. Alternatively you can consider using a part of the JSON document. I.e., instead of defining:
{
type: "user",
firstname: "John",
lastname: "Smith"
}
You would have:
{
user: {
firstname: "John",
lastname: "Smith"
}
}
And then in the view for emitting documents containing `user` information, instead of using:
function (doc) {
if (doc.type === "user") emit(null, doc);
}
You would write:
function (doc) {
if (doc.user) emit(null, doc);
}
As you can see there is not much difference. As you have already realized 1st approach is the most widely used but second (afaik) is well accepted.
Regarding the question of storing all `Posts` of one `User` in one single document. Depends on how you plan to update your document. Remember that you need to write the whole document each time that you update (unless you use `attachments`). That means that each time a user writes a new `Post` you need to retrieve the document containing the `array` of `Posts`, add/modify one element and update the document. Probably too much (heavy).
Problem
I'm trying to wrap my head around `CouchDB`. I'm trying to switch off of `MongoDB` to `CouchDB` because I think the concept of `views` are more appealing to me. In `CouchDB` it looks like all records are stored in a single database. There is no concept of collections or anything, like in `MongoDB`. So, when storing different data entities such as users, blog posts, comments, etc, how do you differentiate between them from within your map reduce functions? I was thinking about just using some sort of `type` property and for each item I'd just have to make sure to specify the `type`, always. This line of thought was sort of reinforced when I read over the `CouchDB` cookbook website, in which an example does the same thing. Is this the most reliable way of doing this, or is there a better method? I was thinking of alternatives, and I think the only other alternative way is to basically embed as much as I can into logical documents. Like, the immediate records inside of the database would all be `User` records, and each `User` would have an array of `Posts`, in which you just add all of the `Posts` to. The downside here would be that embedded documents wouldn't get their own `id` properties, correct?