First of all, let me start by providing my MongoDB schema.
showTitle: String,
seasons: [{
seasonNumber: String,
episodes: [{
episodeNumber: String,
episodeTitle: String,
episodeSynopsis: String
}]
}]
The basic idea for this collection is to store tv show details. The TV shows can contain multiple seasons and each seasons contain multiple episodes.
I am allowing users to add additional seasons(only seasonNumber) at the client side. This will pass a value to the server side. This part works just fine as I can view the value, a string when I console.log at my server side.
Here, my API calls this particular function.
function saveReport(err, res, count, seasonId, seasonDetails)
{
if(count == 0) //if 0 means not exist, so can add into DB
{
Show.update({_id: seasonId},{$push: {seasons:{seasonNumber: [seasonDetails]}}}, {upsert:true}, function(err, result)
{
console.log(result);
res.json(result);
});
}
else
{
res.json("TV Season already exists in MongoDB");
}
}
module.exports.seasonsCreate = function(req, res)
{
console.log("Calling the seasonsCreate function");
var seasonId = req.params.id;
var seasonDetails = req.body.season; //season number as a string(intended)
//finding a specific showing using the id passed as parameter
//$elemMatch is used to check if season number exists
//using count to determine
Show.findOne({_id: req.params.id, seasons: {$elemMatch: {seasonNumber: req.body.season}}}).count(function(err, count)
{
saveReport(err, res, count, seasonId, seasonDetails);
});
}
I manually(using MongoDB command) added two seasons into MongoDB. Season 1 and Season 2 with 2 episodes each. However, when I try to add a 3rd episode via the client side, nothing happens. The exact result being returned is this:
Object {ok: 0, n: 0, nModified: 0}
I've done updating before using a similar method. However, I'm a bit thrown off because this time I have nested arrays instead of just objects. I've also tried several combinations:
- with/without push
- with/without set
- with/without upsert
I'm pretty sure the problem is the way I am updating my database. Hope someone can shed some light here. Thanks !!
p/s: I'm using latest version of Mongoose.
$push, but other update operations are not so straightforward. I would strongly suggest to not use a nested array and figure a way to model differently.$pushwill append to whatever content is in the array on update. What you are suggesting will overwrite any changes that were issued in between the.find()and the.save()