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.