Skip to content

Instantly share code, notes, and snippets.

@MichaelSEA
Created April 11, 2014 05:02
Show Gist options
  • Save MichaelSEA/10441656 to your computer and use it in GitHub Desktop.
Save MichaelSEA/10441656 to your computer and use it in GitHub Desktop.
mongoose models - trying to determine second-level populate issue
// ... requires elided...
var UserSchema = new Schema({
name: String,
email: String,
username: {
type: String,
unique: true
},
provider: String,
hashed_password: String,
salt: String,
});
mongoose.model('User', UserSchema);
var CommentSchema = new Schema({
created: {
type: Date,
default: Date.now
},
modified: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
required: true,
ref: 'User'
},
content: {
type: String,
default: '',
trim: true
}
});
CommentSchema.statics = {
load: function(id, cb) {
this.findOne({
_id: id
}).populate('user', 'name username').exec(cb);
}
};
mongoose.model('Comment', CommentSchema);
var OpinionSchema = new Schema({
created: {
type: Date,
default: Date.now
},
modified: {
type: Date,
default: Date.now
},
content: {
type: String,
default: '',
trim: true
},
// user for opinion -- required
user: {
type: Schema.ObjectId,
required: true,
ref: 'User'
},
// comments on opinion
comments: [ { type: Schema.ObjectId, ref: 'Comment' } ]
});
OpinionSchema.statics = {
load: function(id, cb) {
this.findOne({
_id: id
})
.populate('user', 'name username')
.populate('comments')
.exec(cb);
}
};
mongoose.model('Opinion', OpinionSchema);
var PostSchema = new Schema({
created: {
type: Date,
default: Date.now
},
modified: {
type: Date,
default: Date.now
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
image_url: {
type: String,
default: '',
trime: true
},
opinions: [ { type: Schema.ObjectId, ref: 'Opinion' } ]
});
PostSchema.statics = {
load: function(id, cb) {
this.findOne({
_id: id
})
.populate('user opinions')
.exec(cb);
}
};
mongoose.model('Post', PostSchema);
@MichaelSEA
Copy link
Author

the goal here is to populate Post model such that:

  • Post.user info is included through ObjectId (works)
  • detail for each of Post.opinions is included through ObjectIds (works)
  • detail for post.opinions[n].user is shown for each opinion.user (doesn't yet work)
  • detail for post.opinion[n].comments -- including the comment.user -- is shown (dosn't yet work)

so in short my issue is that I need to show detail from sub-subdocuments on Post through .populate :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment