3

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?

Benzon
  • 119
  • 6
  • Would the values of `req.body.category` and `req.body.description` be null as well when you do an update? – chridam Nov 09 '15 at 20:50
  • thats the issue i guess on, use body-parser for this. But it's wird that in the video course his values dos not go null even tho he updates via the same method Rest Easy via Firefox – Benzon Nov 09 '15 at 20:59

1 Answers1

1

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

Community
  • 1
  • 1
Abdullah Rasheed
  • 3,562
  • 4
  • 33
  • 51
  • Ye thought so updating tur Rest Easy/Firefox, with ex. { name: "Test" } And then the other values go null is there a way to avoide this issue?, just wondering how the heck he made it work on his video, how he avoide thos null values, since it's the same code. – Benzon Nov 09 '15 at 21:00
  • @chridam this should be the default behavior right? – Abdullah Rasheed Nov 09 '15 at 21:08
  • Could be related to this [**issue**](http://stackoverflow.com/questions/24755452/) – chridam Nov 09 '15 at 21:16
  • @SørenBenzonEskildsen are you using bodyParser middleware? in your app configuration do you have: `app.use(bodyParser.json());` `app.use(bodyParser.urlencoded({ extended: true }));` – Abdullah Rasheed Nov 09 '15 at 21:51