I'm running into an issue where mongoose won't remove embedded docs when I'm editing an existing document. I've got a schema of Server that can have any number of embedded docs called services. I'm running into a problem though where, even though I've successfully removed the individual service from the server object, when I tell it to save it just doesn't remove it. The save function is working because it's saving any content changes I've made and is also pushing new embedded docs in, it's just not removing existing ones.
Here is a simplified example:
app.put('/server/:id', function(req, res, next){
app.Server.findOne({_id: req.params.id}, function(err, server) {
server.updated = new Date();
...
for (var num = _.size(req.body.server.services) - 1; num >= 0; num--){
// Is this a new service or an existing one
if (server.services[num]) {
// Is it marked for deletion? If so, delete it
if (req.body.server.services[num].delete == "true") {
server.services[num].remove()
} else { // else, update it
server.services[num].type = req.body.server.services[num].type
...
}
} else {
// It's new, add it
delete req.body.server.services[num]["delete"]
server.services.push(req.body.server.services[num]);
}
}
server.save(function(err){
if (!err) {
req.flash('success', 'Server updated')
} else {
req.flash('error', 'Err, Something broke when we tried to save your server. Sorry!')
console.log(err)
}
res.redirect('/')
});
})
});
So the remove() is actually removing that service. If I do a server.toObject() before the save, it's not there.
Any ideas why it wouldn't be removing it when it saves?
Carlos
Sent from my iPhone
Thank you Carlos! You're workaround worked. Splicing out the specific embedded doc instead of removing it works.Anyone have any idea why it would do this? Is the dev team aware? Should I make a ticket?