Usually in mongoose save the object nested, through the father's call method save, but if we have two levels of engagement, grandfather, father [nested], son [nested], the son is not saved through the father's call method save.
Grandfather -> Group
var schema = new mongoose.Schema({
name: String,
days:[mongoose.Schema.Types.Day],
});
module.exports = mongoose.model('Group', schema);
Father -> Day
var schema = new mongoose.Schema({
_id: Number,
matches:[mongoose.Schema.Types.Match]
});
module.exports = mongoose.model('Day', schema);
Son -> Match
var schema = new mongoose.Schema({
team1: {
type: Schema.ObjectId,
ref:'Team'
},
team2: {
type: Schema.ObjectId,
ref: 'Team'
},
score: [Number]
});
module.exports = mongoose.model('Match', schema);
In the routes ("matches.js") I try to save the group jointly day and match.
Group.findById(groupId).exec(
function(err, group){
var match = new Match();
var day = group.days[dayNumber-1];
day.matches.push(
match
);
group.save(function(err){
console.log("success");
console.log("group in matches.js:"+group);
res.redirect("/tournaments/"+tournamentId+"/groups/"+groupId+"/days/"+dayNumber);
});
});
In the redirect I print again the "group" and the match disappears.
app.get('/tournaments/:tournamentId/groups/:groupId/days/:dayNumber', function (req, res) {
groupId = req.params.groupId;
dayNumber = req.params.dayNumber;
Group.findById(groupId, function (err, group) {
console.log("group in days.js:"+group);
res.render('days/show', {
title: 'Days',
group: group,
day:group.days[dayNumber-1],
tournamentId: req.params.tournamentId
});
});
});
The console log print:
new match
success
group in matches.js:{ __v: 7,
_id: 53a3ee54dfe793bd9a20c6ab,
name: 'gruppo sdirubbo',
days: [ { matches: [Object], _id: 1 } ] }
GET /tournaments/539f0185ea17e46e73be937b/groups/53a3ee54dfe793bd9a20c6ab/days/1/newMatch 302 4ms - 208b
group in days.js:{ __v: 7,
_id: 53a3ee54dfe793bd9a20c6ab,
name: 'gruppo sdirubbo',
days: [ { matches: [], _id: 1 } ] }