Search code examples
node.jsmongodbexpressmongoosemongoose-populate

Mongoose referring to Comment and to it child Users


I'm working on my personal project which is just simple blog and I got stuck with this problem:

I have 3 Mongoose Schemas:

Blog:

var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    description: String,
    body: String,
    created: { type: Date, default: Date.now() },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }
    ]
});

Comment:

var commentSchema = new mongoose.Schema({
    text: String,
    author_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }
});

User:

var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    avatar_url: String,
    email: String
});

And in each blog post I'm trying to display comments from array which is working correctly but then I don't know how to access to User model to display usernames and avatar_urls

app.get("/blogs/:id",function(req,res){
    Blog.findById(req.params.id).populate("comments").populate("author_id").exec(function(err,findBlog){
        if(err){
            res.redirect("back");

            console.log(err);
        }else{
            res.render("show" , {blog: findBlog});
        }
    })
})

Solution

  • you have to declare user information like username in the blog schema then only you can send request to userschema for avatar_url