Reputation: 129
Currently doing a online course to learn some Node.js, Express, and MongoDB.
In this course there is a api section where they teach you to do simple stuff, but i ran in to an issue, the course video shows him updating name of an item, and the api makes it possible to update more fields, his fields keep there value, my fields actually end up being null.
The code is
app.put('/products/:id', function(req, res){
db.products.findAndModify({query: {_id: mongojs.ObjectId(req.params.id)},
update:{$set:{
name: req.body.name,
category: req.body.category,
description: req.body.description
}},
new: true
}, function(err, doc){
if(err){
res.send(err);
} else {
console.log('Updating Product...');
res.json(doc);
}
});
});
Can any one explain to me how i avoid lets say category and description ending up being null if only the name is updated?
Upvotes: 3
Views: 194
Reputation: 3752
If req.body.category
and req.body.description
are undefined
in your code:
update:{$set:{
name: req.body.name,
category: req.body.category,
description: req.body.description
}},
your fields will be set to null
on the matching document.
See the mongodb set null in update and set field as empty for mongo object using mongoose
Upvotes: 1