How to save boolean value from checkbox with mongoose and express?

I cannot imagine a simple way to preserve a boolean value using expression and mongoose. I have this circuit:

var ClientSchema = new Schema({ name: {type: String, required: true, trim: true}, active: {type: Boolean } }); var Client = mongoose.mode('Client', ClientSchema); 

These are my controllers.

 exports.new = function(req, res) { var client = new Client(); res.render('clients/new', { item: client } ); }; exports.create = function(req, res) { var client = new Client(req.body); client.save(function(err, doc) { if (err) { res.render('clients/new', { item: client }); } .... }); }; 

And this is my opinion

 form(method='post', action='/clients', enctype='application/x-www-form-urlencoded') input(type='text', name='name', value=item.name) input(type='checkbox', name='active', value=item.active) 

Mongoose has the ability to map parameters to req.body. In the line var client = new Client (req.body), the client has a property name created from req.body with the correct value passed from the form, but the active property does not reflect the state of the flag.

I know I can solve this problem by adding this line after var client = new Client (req.body), but I have to do this for every checkbox that I add to my forms:

 client.active = req.body.active == undefined ? false : true; 

Modified Question

I do not need to do this ruby ​​trick on rails. How to use flags without adding the previous line for each flag? Is this the only way to save values ​​from checkboxes or is there an alternative?

Edit

I have another case where a circuit is defined this way

 var ClientSchema = new Schema({ name: {type: String, required: true, trim: true}, active: {type: Boolean, default: true } }); 

Note that true is active by default, so if you uncheck the box, it will be activated true, not false.

+6
source share
1 answer

Ruby on rails will display a hidden field next to the check box:

 <input name="model_name[field_name]" type="hidden" value="false"> <input id="model_name_field_name" name="model_name[field_name]" type="checkbox" value="true"> 

This is because checkboxes that are not checked do not send mail data. See Is <input type = "checkbox" /> only post data if checked? More on this.

The trick here, according to RoR, is a hidden field, and the flag has the same meaning for the name attribute. If the check box is selected, the value of the check box will be sent as post data, otherwise the value of the hidden field will be sent.

This was, of course, in RoR version 3.x

Further information on this "getcha" can be found here: http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box

You need to either implement such things in your node application, or check for undefined as you were.

+1
source

All Articles