Miha Šušteršič Miha Šušteršič - 1 month ago 16
Node.js Question

mongoose Model.update() - only update provided values

I have the following schema:

const wordSchema = mongoose.Schema({
author: {type: String, index: true, default: 'unknown'},
quote: String,
source: {type: String, default: 'unknown', index: true},
rating: {type: Number, default: 0},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});


And the following PUT route in my express app:

// Route to update a quote in the DB
app.put('/words/:id', function(req, res) {
const quote = new Word({
_id: req.params.id,
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
rating: req.body.rating,
updatedAt: Date.now(),
});
Word.update(quote, function(err, raw) {
if (err) {
res.send(err);
}
res.send(raw);
});
});


Now when I send the PUT request, if the parameters set with a default value are not provided, they will be filled with the default values from the Schema. How do I update only the provided values?

Thanks for the help.

Answer

Don't create a new Word instance for the update, update takes conditions and doc object parameters that let you separately identify the document to update and provide its updated values:

app.put('/words/:id', function(req, res) {
  const doc = {
    author: req.body.author,
    quote: req.body.quote,
    source: req.body.source,
    rating: req.body.rating,
    updatedAt: Date.now(),
  });
  Word.update({_id: req.params.id}, doc, function(err, raw) {
    if (err) {
      res.send(err);
    }
    res.send(raw);
  });
});