mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Can't set Boolean to undefined

Open aerkmukdahan opened this issue 6 years ago • 4 comments

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

I have doc.booleanField = true and I want to remove this key from my document by this below code

doc.booleanField = undefined
doc.save()

But the result is doc.booleanField = null and the key isn't removed

What is the expected behavior?

It should able to set boolean field to undefined and can use doc.save() to remove it form doc

I was able to remove boolean field by this way until mongoose update to version 5.9.24

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

Node: 10.20.1 Mongoose: 5.9.25 MongoDB: 4.0.18

aerkmukdahan avatar Jul 23 '20 04:07 aerkmukdahan

This was introduced by allowing null as a valid property for booleans and it is breaking our code as well. ☹️

kevinsandow avatar Jul 23 '20 06:07 kevinsandow

Related to this https://github.com/Automattic/mongoose/issues/9253

josephstgh avatar Jul 24 '20 10:07 josephstgh

This was introduced by allowing null as a valid property for booleans and it is breaking our code as well. frowning_face

@KevinBusse null has always been a valid value for booleans. This is a regression somehow introduced in 5.9.24.

sgpinkus avatar Jul 25 '20 02:07 sgpinkus

Here is a test script for this issue:

const mongoose = require('mongoose');
const { Schema } = mongoose;

async function test() {
  var Test  = mongoose.model('Test', new Schema({ a: Boolean }));

  // TEST 1: INITIALIZATION:
  console.log(new Test({ a: undefined })); // 5.9.23: {}, 5.9.24: { a: null }

  // TEST 2: UPDATE AFTER SAVE:
  await mongoose.connect('mongodb://localhost/test', {});
  var x = new Test({ a: true });
  await x.save();
  x = await Test.findById(x);
  console.log(x);
  x.a = undefined;
  await x.save();
  x = await Test.findById(x);
  console.log(x);  // 5.9.23: {}, 5.9.24: { a: null }
}

test().then(() => process.exit()).catch((e) => { console.error(e); process.exit(); })

sgpinkus avatar Jul 25 '20 02:07 sgpinkus