Reputation: 7162
I have the following schema where I am trying to add an array of comments to my blog post schema, then inside the comments schema I need to add an array of pictures urls related to each specific comment. I've researched the web and found this link embedded documents to mongoose documentation, yet noticed that it is related to mongoose version 2.7 while we are currently at version 3.8. So was wondering if I am doing it right?, and if not can someone please help me by suggesting the best way for designing my blog post schema so that it includes the blog post array of comments as well as the array of pictures related to each comment. Thanks for your time and effort.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var pictures = new Schema({
picURL: String,
date: {
type: Date,
default: Date.now
}
});
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[pictures]
});
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments:[comments]
});
module.exports = mongoose.model('BlogPost', blogpost);
Upvotes: 3
Views: 3321
Reputation: 16056
you have two common scenarios here how you would like to handle your information
Embedded document:
if you are likely to do more reads than writes it's recommended to follow this approach in this case your model could be like this:
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[{
picURL: String,
date: {
type: Date,
default: Date.now
}
}]
});
and also your approach to me is ok and should run on 3.8 without potential issues.
Referenced document:
if you'll have more writes than reads you can different collections to split the information and make a reference to your objectId like:
var comments = new Schema({
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures: [
{type: Schema.Types.ObjectId, ref: 'pictures'}
]
});
you'll need to separate each schema into it's own and delare a model for comments and images as well.
Either way both are valid if you ask me my personal preference is picking up embedded document approach.
EDIT:
this situation can be applied for N relationships between collections, I keep it simple for two relationships, but for you scenario could be like this:
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments: [{
subject: String,
body: String,
date: {
type: Date,
default: Date.now
},
pictures:[{
picURL: String,
date: {
type: Date,
default: Date.now
}
}]
}]
});
referenced:
var blogpost = new Schema({
title: String,
body: String,
date: {
type: Date,
default: Date.now
},
comments:type: Schema.Types.ObjectId, ref: 'comments'}
});
hope that helps.
Upvotes: 5