Intellipaat 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

2 Answers

0 votes
by (107k 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

});

0 votes
by (1.2k points)

We can do it using `ref` functionality within the schema definition. This will give us leverage to establish the relationship between these two different models. 

Once, you have defined your schema that we need to reference i.e, Let’s say user and post model, so our schema goes like this:

const mongoose = require(“mongoose”)

Const { Schema }  = mongoose 

const user_schema = new Schema({

name : string,

email_address : string,

});

# Posting Schema for User’s model

const post_schema = new Schema({

headline: string,

body : string, 

author: { type : Schema.Types.ObjectId, ref = “User”}); # Here we are referencing user model

# Working with the models

const User_Model = mongoose.model(“User”, user_schema);

const Post_Model = mongoose.model(“Post”, post_schema);

Related questions

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...