1

I have a User Model

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    } 
    email: {
        type: String,
        required: true,
        maxlength: 128,
        minlength: 5
    }, 
    hashedPassword: {
        type: String,
        required: false
    }
});

module.exports = mongoose.model('users', UserSchema);

And a Post Model

const mongoose = require('mongoose');

const PostSchema = new mongoose.Schema({
    description: {
        type: String,
        required: true
    },
    comments: [{
        comment: {
            type: String,
            required: true
        },
        postedBy: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'users'
        },
        postedOn: {
            type: Date,
            required: true,
            default: Date.now
        }
    }],
    postedBy: {
        type: mongoose.Types.ObjectId,
        required: true,
        ref: 'users'
    }
});

module.exports = mongoose.model('answers', AnswerSchema);

I want to fetch post with populated "postedBy"(of POST) also select fields of "name and email" from "postedBy"(of POST). Also, I want to populate "postedBy"(inside comments) and select the same field of "name and email" from "postedBy"(inside comments).

Expecting to see a result like

{
    "post": [
        {
            "_id": "*some mongo id*",
            "description": "This is a sample Post for testing",
            "postedBy": {
                "_id": "5e9285669bdcb146c411cef2",
                "name": "Rohit Sharma",
                "email": "rohit@gmail.com"
            },
            "comments": [{
                "comment": "Test One Comment",
                "postedBy": {
                    "_id": "5e9285669bdcb146c411cef2",
                    "name": "Rohit Sharma",
                    "email": "rohit@gmail.com"
                },
            }],
            "postedOn": "2020-04-19T12:28:31.162Z"
        }
    ]
}

0 Answers0