Я пытаюсь сохранить данные в базе данных команд на следующем примере модели.Это вложенный массив объектов 3-го уровня для MongoDB с использованием Mongoose.
const teamSchema = new Schema({
name: {
type: String,
required: true
},
who: {
type: String,
required: true
},
textManifesto: {
type: String,
required: false
},
videoManifesto: {
type: String,
required: false
},
competencies: {
competency: [{
type: Schema.Types.ObjectId,
ref: 'Competency',
required: true
}]
},
members: [{
member: {
type: Schema.Types.ObjectId,
ref: 'Applicant',
required: true
},
position: {
type: String,
required: true
},
memberCompetencies: {
competency: [{
type: Schema.Types.ObjectId,
ref: 'Competency',
required: true
}]
},
evaluatedCompetencies: {
competency: [{
type: Schema.Types.ObjectId,
ref: 'Competency',
required: false
}]
}
}],
},
Я в основном использовал метод push, чтобы поместить элементы массива в переменную и затем попытаться сохранить в базе данных, но база данных пустадля членов.Он просто показывает и пустой массив.
//Map Team Competencies
for (let competency of teamCompetencies) //array is your array variable, i suppose
newTeamCompetencies.push({ competency: competency, _id: mongoose.Types.ObjectId() });
//console.log(newTeamCompetencies);
//Map My Competencies
for (let competency of myCompetencies) //array is your array variable, i suppose
newMyCompetencies.push({ _id: mongoose.Types.ObjectId(), competency: competency });
// console.log(newMyCompetencies);
team = await new Team({
name: teamName,
textManifesto: textManifesto,
who: who,
});
//save collective expected competencies of team
team.competencies = newMyCompetencies;
//save member details
team.members = ({
member: res.locals.applicant._id,
position: 'Leader',
memberCompetencies: newMyCompetencies,
})
team = await team.save();
console.log(team.members);
Ожидаемый результат
[{"memberCompetencies":{ '0':
{ _id: 5d1e128b2a9f1c74907e5ba9,
competency: '5d1dd97206660707754eefb3' },
'1':
{ _id: 5d1e128b2a9f1c74907e5baa,
competency: '5d1dd9d506660707754eefb4' } },,"evaluatedCompetencies":{"competency":[]},"_id":"5d1e1393f640587531b0fd48","member":"5d19999df6f9c678e891af14","position":"Leader"}]
Фактический результат
[{"memberCompetencies":{"competency":[]},"evaluatedCompetencies":{"competency":[]},"_id":"5d1e1393f640587531b0fd48","member":"5d19999df6f9c678e891af14","position":"Leader"}]