From dc54e8d545b89766c30ac0caf447bc75dcb226f0 Mon Sep 17 00:00:00 2001 From: Joel Scheuner Date: Tue, 18 Sep 2018 14:32:01 +0200 Subject: [PATCH] Add PATCH /camels/:id with find and update API Alternative patch implementation using Mongoose `findByIdAndUpdate`: https://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate Notice: The `new` determines whether to return the new (i.e., updated) version (default: false) Caveats: Mongoose is in the process of changing their API: https://github.com/Automattic/mongoose/issues/6922#issue-354147871 To fix the deprecation warnings, we need to set: ```js mongoose.set('useFindAndModify', false); ``` --- app.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app.js b/app.js index b2648bb..3161458 100644 --- a/app.js +++ b/app.js @@ -4,6 +4,7 @@ var mongoose = require('mongoose'); var app = express(); var Schema = mongoose.Schema; // Connect to MongoDB +mongoose.set('useFindAndModify', false); mongoose.connect('mongodb://localhost:27017/animals', { useNewUrlParser: true }); // Parse requests of content-type 'application/json' @@ -68,14 +69,14 @@ app.put('/camels/:id', function(req, res, next) { // Partially update the camel with the given ID app.patch('/camels/:id', function(req, res, next) { var id = req.params.id; - Camel.findById(id, function(err, camel) { + var update = req.body; + // `new` determines whether to return the new (i.e., updated) version (default: false) + var options = {new: true}; + Camel.findByIdAndUpdate(id, update, options, function(err, camel) { if (err) { return next(err); } if (camel == null) { return res.status(404).json({"message": "Camel not found"}); } - camel.color = (req.body.color || camel.color); - camel.position = (req.body.position || camel.position); - camel.save(); res.json(camel); }); });