Reputation: 1003
It seems logical to me to do something like the following:
var AvatarSchema = new Mongoose.Schema({
type: String,
url: String
});
var UserSchema = new Mongoose.Schema({
avatars: [AvatarSchema],
email: String,
name: String,
salt: String,
token: String
});
var ThinUserSchema = new Mongoose.Schema({
avatars: [AvatarSchema],
email: String,
firstname: String,
lastname: String,
});
var QuestionSchema = new Mongoose.Schema({
question: String,
users: [ThinUserSchema]
});
Then later on. . .do something like the following:
var question = new Question({
question: 'Wut?',
users: users //where users is an array of instances of a user model of the UserSchema
});
Here I would expect the users section of the question to be populated with avatars, emails, firstnames and lastnames. . .however since the users/avatars already have _id, these are not persisted.
What is the proper pattern for these sorts of schemas?
Thanks!
Upvotes: 27
Views: 43761
Reputation: 8111
I believe you are correct in your assumptions, it's called Embedded documents in Mongoose, here is the example from the Mongoose documentation.
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('BlogPost', BlogPost);
Disclaimer: I wouldn't necessarily put the comma before the items!
Upvotes: 8
Reputation: 4206
I am mongoose noob still and if I understand correctly I think what you need to read is this: http://mongoosejs.com/docs/populate.html
There is a very nice and simple example, where you have referenced schemas in other schemas. So in order to include a document of particular schema inside another, it is better to include it via reference. When you need it, you call populate on parent document. When you change child document, the populated parent will change as well of course.
Upvotes: 4