Заполнение и выбор нескольких поддокументов Мангуста - PullRequest
1 голос
/ 19 апреля 2020

У меня есть Модель пользователя

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);

И Модель сообщения

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);

Я хочу получить сообщение с заполненным " postsBy "(из POST) также выбирает поля" имя и адрес электронной почты "из" postsBy "(из POST). Кроме того, я хочу заполнить "postsBy" (внутри комментариев) и выбрать то же поле "name и email" из "postsBy" (внутри комментариев).

Ожидается увидеть результат, подобный

{
    "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"
        }
    ]
}
...