Saturday, 22 April 2017

Mongoose reffering 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 Im 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});
    }
})

})



via Mateusz Perlak

No comments:

Post a Comment