AFS AFS - 4 months ago 20
Node.js Question

Check empty fields on mongoose

I have this function on my node REST API

var router = express.Router();

/*router.get('/getUsers', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});*/

router.route('/Users')
.get(function(req,res){
User.find(function(err,users){
if(err)
res.send(err);

console.log('GET request');
res.json(users);
});
})
.post(function(req,res){
var user = new User();
user.name = req.body.name;
user.lastName = req.body.lastName;

if(!user.name || !user.lastName){
user.save(function(err){
if(err)
res.send(err);

console.log('POST request');
res.json({message:'Usuario creado'});
});
}else{
res.json({message:'Campos vacíos'});
}

});


It works but when I a send a POST request with empty parameters it saves a document in mongoDB without the
name
and
lastName
fields and
if(!user.name || !user.lastName)
doesn't work to avoid it

Answer

Well
if (!user.name || !user.lastName) ...
checks that at least one of both must be empty / null / undefined and only then saves it - exactly what you describe as your problem :)

So I guess you want something like

if(user.name && user.lastName)...  

Or alternatively swap the code blocks in if / else branch

if(!user.name || !user.lastName){
  res.json({message:'Campos vacíos'});
}else{
  user.save(function(err){
    if(err)
      res.send(err);
    console.log('POST request');
    res.json({message:'Usuario creado'});
  });
}