Reputation: 8295
I am having problem with building up some simple queries with this design. The problem is simple I want get the posts with included user information, which should be all in one array so i can pass it to the express view.
Simple and for me it seems the wrong solution would be after finding all the posts(db.post.find({email:'[email protected]'})
and then looping through the posts and making one find query yo user collection and then merge the results.
Other solution would be using the DBref linking the author this may be better but i haven't found out how to make queries.
// User, the profile is not complete there will be more fields
var u = {
name: 'Michael', // Is not unique
email: '[email protected]', // Should be also unique
fbid: '4545454asdadsa'
}
db.user.insert(u);
// User can have 0 to many posts
var p = {
title: 'Suprise',
body: 'Well done',
tags: ['first', 'post', 'english'],
author: '[email protected]',
created: new Date(),
modified: new Date()
};
db.post.insert(p);
var p = {
title: 'Weather in Estonia',
body: 'Always looks bad',
tags: ['bad', 'weather', 'estonia'],
author: '[email protected]',
created: new Date(),
modified: new Date()
}
db.post.insert(p);
Upvotes: 2
Views: 123
Reputation: 169401
var p = {
title: 'Suprise',
body: 'Well done',
tags: ['first', 'post', 'english'],
author: {
name: 'Michael', // Is not unique
email: '[email protected]', // Should be also unique
fbid: '4545454asdadsa'
},
created: new Date(),
modified: new Date()
};
You embed documents, you denormalize. This is how it works. Now you can just get all the posts and dont have to query for the users because they are already there.
I'll spell out how this can be done. I went completely overboard with the denormalization. This means you never need joins. Note that some of this can be removed if it's just cruft and never needed.
{
title: String,
body: String,
tags: [String],
author: {
name: String,
email: String,
fbid: String
},
created: Date,
modified: Date,
comments: [{
body: String,
created: Date,
modified: Date
}]
}
{
name: String,
email: String,
fbid: String,
posts: [{
title: String,
body: String,
tags: [String],
created: Date,
modified: Date,
comments: [{
body: String,
created: Date,
modified: Date
}]
}]
}
{
body: String,
created: Date,
modified: Date,
author: {
name: String,
email: String,
fbid: String
},
post: {
title: String,
body: String,
tags: [String],
created: Date,
modified: Date
comments: [{
body: String,
created: Date,
modified: Date
}]
}
}
Upvotes: 2