I'm struggling trying to save a subdocument array. Just wont save:
The front end sends up a Day object that has an array of headings, and each heading can have a content array (which is a mongoose schema).
var DaySchema = mongoose.Schema({
date: Date,
startTime: Date,
endTime: Date,
title: String,
order: Number,
description: String,
cohort: {
type: objId,
ref: 'cohort'
},
instructors: [{
type: objId,
ref: 'instructor'
}],
headings: [{
title: String,
subTitle: String,
content: [{
type:objId,
ref: 'content'
}]
}]
});
var ContentSchema = mongoose.Schema({
title: String,
description: String,
contentUrl: String,
dueDate: Date,
dateAssigned: Date,
downloadUrl: String
});
This is the code I'm using to PUT and POST a Day, with its associated Content objects. Everything works except for saving the content. When I look in the mongo shell each content field under headings looks like this:
content: []
Any thoughts?
exports.putdaycontent = function (req, res) {
var dayId = req.params.dayId;
var headings = req.body.headings;
var day = req.body;
var updateDay = function () {
Day.update({_id: dayId}, day, {new: true, upsert: true}, function (err, day) {
if (err)
error.databaseError(req, res, err);
res.send(day);
});
};
if (headings) {
for (var x = 0; x < headings.length; x++) {
var h = headings[x];
if (h.content) {
for (var y = 0; y < h.content.length; y++) {
var c = h.content[y];
//If existing content update it
if (c._id && c._id.length > 0) {
Content.update({_id: c._id}, c, {new: true,upsert: true}, function (err, content) {
});
} else {
var content = new Content(c);
h.content[y] = content;
}
}
}
}
day.headings = headings;
updateDay();
} else {
updateDay();
}
};
exports.postdaycontent = function (req, res) {
var headings = req.body.headings;
var day = req.body;
var cohortId = day.cohort._id;
var postDay = function () {
var d = new Day(day);
console.log("CONTENT DAYS:",d);
d.save(function(err, newDay) {
if (err)
error.databaseError(req, res, err);
Cohort.findOneAndUpdate({_id: cohortId}, {$push: {days: newDay}}, {upsert: true}, function(err, newCohort) {
res.send({msg:"Successfully saved day to cohort"});
});
});
};
if (headings) {
for (var x = 0; x < headings.length; x++) {
var h = headings[x];
if (h.content) {
for (var y = 0; y < h.content.length; y++) {
var c = h.content[y];
var content = new Content(c);
h.content[y] = content;
console.log("CONTENT:",content);
}
}
}
day.headings = headings;
}
postDay();
};
.update()without$setor similar operators. All arrays are referenced so unless the actual objects exist already in another collection you don't create this way. HopefullyobjIdhas been imported fromSchema.Types.ObjectId. Those are just a few thoughts that come to mind at first glance.