Почему не удается сделать обратное преобразование данных из Mongo
Пишу сервис на Express с библиотекой mongoose и базой MongoDB. Я пытаюсь сохранить схему материнской группы в базу. В материнской группе есть параметр дочерние группы, это массив в котором содержатся айдишники указывающие на объекты схемы дочерней группы
Схема дочерней группы
const {Schema, model} = require('mongoose ')
const ChildGroup = new Schema({
groupId: {type: String, required: true},
groupName: {type: String, required: true},
priority: {
type: Number, required: false, validate: {
validator: function (v) {
return 0 < v <= this.study_fields.length;
},
message: props => `${props.value} is greater than study_fields length`
}
}
})
module.exports = model('ChildGroup', ChildGroup)
Схема материнской группы
const {Schema, model} = require('mongoose')
const MotherGroup = new Schema({
groupId: {type: String, required: true},
childGroups: [{type: Schema.Types.ObjectId, ref: 'ChildGroup'}],
})
module.exports = model('MotherGroup', MotherGroup)
Функция обрабатывающая запрос:
const { groupId, childGroups } = req.body;
const existingMotherGroup = await MotherGroup.findOne({ groupId });
existingMotherGroup.childGroups = childGroups.map((group) => new ChildGroup({
groupName: group.groupName, // имя группы - обязательное поле
groupId: group.groupId, // идентификатор группы - обязательное поле
priority: 1, // приоритет можно не указывать
}));
console.log(existingMotherGroup.childGroups)
await existingMotherGroup.save();
const motherGroup = await MotherGroup.findOne({groupId});
console.log(motherGroup)
const asd = await motherGroup.populate({path: 'childGroups', model: 'ChildGroup'})
console.log(asd.childGroups)
res.status(200).json({ message: 'Child groups added to existing mother group' });
Собственно console.log(asd.childGroups) выводит мне пустой массив. В то время как const motherGroup = await MotherGroup.findOne({groupId});, содержит параметр childGroups, в котором есть айдишники.
Как вытащить именно объекты из базы, а не айдишники ?
Сразу скажу, что при console.log(existingMotherGroup.childGroups) массив childGroup отображается нормально, то есть сохраняется корректно, так что скорее всего дело не в этом