Last week, I searched for and struggled to implement an upsert call for my CompHound and FireRating samples, i.e. a REST PUT call that does both PUT to update the data of an existing record as well as POST to create a new record, if none exists.
I ended up implementing the
update2 function calling
the mongoose findOne
function and then selecting either update
or create
based on whether an existing record is found.
Luckily, I asked my colleague
Philippe Leefsma to
review this, and he found a StackOverflow discussion on
mongodb: insert if not exists that
mentions a much easier solution, adding an argument specifying the options {upsert:true}
to the update
call.
That is exactly what I had searched for, fruitlessly, high and low.
After learning about the existence of this, I finally also found the official mongodb upsert Option documentation on it.
I implemented a new, simpler, update3
function making use of it, and it works flawlessly:
exports.update3 = function(req, res) { var id = req.params.id; console.log('Updating ' + id); Door.update({"_id":id}, req.body, {upsert:true}, function (err, numberAffected) { if (err) return console.log(err); console.log('Updated %s instances', numberAffected.toString()); return res.sendStatus(202); }); };
I added this to the fireratingdb repo and updated it to release 0.0.13.
I obviously also redeployed it to heroku, where it is running at fireratingdb.herokuapp.com.
Many thanks to Philippe for noticing and pointing this out!