D
D
dollaween2019-02-27 15:49:12
MongoDB
dollaween, 2019-02-27 15:49:12

How to change empty Booleans to false in mongodb?

Let's say we have this simple form:

<form action="/add">
  <input type="checkbox" name="placed">
</form>

And such a scheme:
let schema = new Schema({
  placed: {
    type: Boolean,
    default: false,
    required: true
  }
});

When submitting this form, if the checkbox is active (checked), then everything is saved as it should (placed === true). But if you uncheck the checkbox, then placed in the database does not change to false.
The code is built in such a way that if you uncheck the checkbox, then the placed field is not sent at all.
How can I make it so that when an empty field of type Boolean is received, it is automatically saved as false in mongo?
No change in HTML

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollaween, 2019-02-27
@dollaween

I solved the issue by inventing the bicycle:
I forcibly added all unchecked checkboxes to FormData via append with a value of false.
More or less like this:

let data = new FormData(form);
let checkboxes = form.querySelectorAll("input[type='checkbox']");

for (let i = checkboxes.length - 1; i >= 0; i--) {
  data.append(checkboxes[i].name, checkboxes[i].checked);
}

This is of course redundant code, but I did not find another solution :(

A
Andrey Okhotnikov, 2019-02-27
@tsepen

Your placed field is required - required: true, so if nothing comes, then there will be no changes. Try to remove required: true, then if nothing comes it will be false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question