简体   繁体   中英

How can I set Boolean property to true or false in MongoDB with nodejs

I am new to backend development. I am using nodejs with express and mongoose I have successfully updated mongodb with data from a form that mainly contains text so <input type="text value="abcdefg"> seems to work fine.

I have a property field isActive which I'd like to be boolean and have a value of true or false

I tried to do this

<input type="text" value="true">

And I think this is wrong based on some googling ( https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes ) which mentioned that "The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether." .. so I tried the checkbox method

<input type="checkbox" checked>

but here I get value = 'on' and it still gives me some error in the console

messageFormat: undefined,
stringValue: '"on"',
kind: 'Boolean',
value: 'on',
path: 'isActive',
reason: CastError: Cast to boolean failed for value "on" (type string) at path "undefined"

Could someone please advise me on how does one define an input field to get a true or false value in Mongodb?

Answering my own question, just in case it helps someone who is a newbie into backend development like me.

As regular input variables follow this format when the server receives a request

databaseObject.name = request.body.name

I assumed that even for a boolean value, it's the same method so I was trying to do this.

databaseObject.isActive = request.body.isActive where the isActive in the form was the result of a checkbox field.

What worked for me was this..

databaseObject.isActive = request.body.isActive == "on" ? true : false;

As the checkbox returns "on" when it is checked and not true

This might be obvious to others but it wasn't to me.. so maybe this response might help some people out there who might try to assign all values from inputs directly into the object that's being saved into the database.

If there's another way to do this, I would welcome some more answers as this is what I figured out as there was no response to my question. So a better answer or a confirmation that the above is correct would be welcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM