Search code examples
mongodbexpresswebmongoosebackend

Get specific keys and values in the response cycle


// const cookieParser = require("cookie-parser")
const Post = require("../models/post");
// const   User= require("../models/user")

module.exports.home= async(req, res)=>{
    try{
        console.log(req.cookies)
        const posts = await Post.find({})
        .populate("users")
        .populate({
            path:'comments',
            populate:{
                path:'user',
            }
        })
        .exec();
        // console.log(posts.content);
        // console.log(posts);

        //    res.cookie("user_id", 25);
        return res.render('home', {
        title: "Home Page ",
        posts:posts,
    }) 

    }
    catch(err){
        console.log("error in sending feed", err);
        return res.redirect("back");

    }
}

In the response i am getting the name , email , body and password of the person who made the comment but i want only the name to come in the in the response how can i fix that

Source code link :- https://github.com/himanshugupta2168/Codeial


Solution

  • You can use the select option to only pick the properties you want. Update like so:

    const posts = await Post.find({})
            .populate("users")
            .populate({
                path:'comments',
                populate:{
                    path:'user',
                    select: 'name -_id'
                }
            })
    

    Note that the _id is always returned so you can explicitly deselect it with -_id. See docs for further reading.