Skip to content

Commit

Permalink
Add PATCH /camels/:id with find and update API
Browse files Browse the repository at this point in the history
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: Automattic/mongoose#6922 (comment)
To fix the deprecation warnings, we need to set:

```js
mongoose.set('useFindAndModify', false);
```
  • Loading branch information
joe4dev committed Sep 18, 2018
1 parent 4ee87ae commit dc54e8d
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions app.js
Expand Up @@ -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'
Expand Down Expand Up @@ -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);
});
});
Expand Down

0 comments on commit dc54e8d

Please sign in to comment.