F
F
faleaksey2021-07-07 12:18:39
MongoDB
faleaksey, 2021-07-07 12:18:39

How to write an aggregation with a population of data for the following model?

There are 2 models (Post and Author) that are passed using refPath to Data:

Data model:

import { model, Schema, Types } from 'mongoose';

const DataSchema = new Schema({
    page: { type: Types.ObjectId, ref: 'Page', required: true },
    instance: {
        type: Schema.Types.ObjectId,
        required: true,
        // Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
        // will look at the `onModel` property to find the right model.
        refPath: 'fields'
    },
    fields: {
        type: String,
        required: true,
        enum: ['Post', 'Author']
    }
});

export const Data = model('Data', DataSchema);


Post model and author:
import { model, Schema, Types } from 'mongoose';

const PostSchema = new Schema({
    title: String
});

export const Post = model('Post', PostSchema);


import { model, Schema, Types } from 'mongoose';

const AuthorSchema = new Schema({
    name: String
});

export const Author = model('Author', AuthorSchema);


there is a query like this
const allData = await Data.find({ page: { $in: [...pages] } }).populate(['instance', 'page']);

but gives the whole date for all pages in one answer, but for good it needs to be divided into groups like:
[{страница, дата этой сраницы}, {страница, дата этой сраницы}, {страница, дата этой сраницы}]


I know that it is possible to somehow solve this using aggregation, but over the past 24 hours it has not been possible to write a correct query (
!!! IMPORTANT !!! so that all data in the array is brought to the form of documents (populate)

Solved the issue using $ match, $lookup, $group, $project
but without success(

How to implement such a request ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question