Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

Let suppose I am having 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 combine them together like the example above but I couldn't understand how to do it. Ultimately, if I can do something like this it would make my life very easy

var profilePic = Post.postedBy.profilePic

1 Answer

0 votes
by (108k points)
edited by

First of all you have to make a small change to your postSchema, refer the following schema structure:

var postSchema = new Schema({

    name: String,

    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},

    dateCreated: Date,

    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],

});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Now you can populate references with the help of the following command:

Post.findOne({_id: 123})

.populate('postedBy')

.exec(function(err, post) {

    // do stuff with post

});

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...