if I have two schemas like:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var User = mongoose.model('User')
var postSchema = new Schema({
name: String,
postedBy: User, //User Model Type
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
I tried to connect them together like the example above but I couldn't figure out how to do it. Eventually, if I can do something like this it would make my life very easy
var profilePic = Post.postedBy.profilePic
This question is related to
javascript
mongodb
mongoose
Late reply, but adding that Mongoose also has the concept of Subdocuments
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing
Source: Stackoverflow.com