A
A
Alexey Miroshnichenko2019-03-11 19:39:09
MongoDB
Alexey Miroshnichenko, 2019-03-11 19:39:09

How to get elements from child model and add them to parent?

Parent Schema

const taskSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  startDate: {
    type: Date,
    required: true
  },
  description: {
    type: String,
  },
  dateOfCreation: {
    type: Date,
    default: Date.now
  },
  dateOfUpdate: {
    type: Date,
  },
  status: {
    type: String,
    enum: ['inactive', 'active', 'done'],
    default: 'inactive'
  },
  subtasks: [{
    type: Schema.Types.ObjectId,
    ref: 'subtasks'
  }]
});
module.exports = mongoose.model('tasks', taskSchema);

Child Schema
const subtaskSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  parentId: {
    ref: 'tasks',
    type: Schema.Types.ObjectId,
    required: true
  },
  startDate: {
    type: Date,
    required: true
  },
  description: {
    type: String,
  },
  dateOfCreation: {
    type: Date,
    default: Date.now
  },
  dateOfUpdate: {
    type: Date,
  },
  status: {
    type: String,
    enum: ['inactive', 'active', 'done'],
    default: 'inactive'
  }
});
module.exports = mongoose.model('subtasks', subtaskSchema);

How to get tasks with subtasks inside at the output?
For example:
{
dateOfCreation: "2019-03-11T14:12:52.383Z"
description: "desc!!!222asdasd"
startDate: "2019-03-11T10:00:49.669Z"
status: "inactive"
subtasks: [ МАССИВ ИЗ SUBTASKS ]
title: "4444 edited sss"
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alisher Aidarkhan, 2019-03-12
@alikenski

Read about deepPopulate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question