Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

empty objects are being saved as null #14596

Closed
2 tasks done
matanDevalore opened this issue May 16, 2024 · 1 comment
Closed
2 tasks done

empty objects are being saved as null #14596

matanDevalore opened this issue May 16, 2024 · 1 comment

Comments

@matanDevalore
Copy link

matanDevalore commented May 16, 2024

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.2.4

Node.js version

20.12.0

MongoDB server version

6.0.2 Community

Typescript version (if applicable)

5.4.3

Description

I have a schema which accepts an Object property.
image

On mongoose version 8+, when updating the document in DB, with an empty object ( {} ), the value that is actually being saved is null.

image

when querying the DB and fetching the relevant document, variables: null is being returned, which makes other validations in the system to throw the following error:
image

On older versions (tested on 7.6.3), it doesn't happen and it behave as expected (the object is being saved as an empty object):

image

I can ofc changing the validators in the system, but it seems like the wrong solution. empty object doesn't equal to null.

Steps to Reproduce

  1. create a mongoose model with an object field. for example:
const TestSchema = new Schema({
  data: {
    type: Object,
  },
});

export const TestModel = mongoose.model('Test', TestSchema);
  1. create a new document in DB (with empty object: data: {}). (the object will be saved without data property - which is fine)
  2. load this document using findOne.
  3. reset the data field again to empty object: document.data = {}
  4. save this document using document.save()

Expected Behavior

after update, the data field should be an empty object {}. as can see using mongoDB Compass in old mongoose versions:

image

another good solution for me, is if you will add a new parameter that will allow me to choose the way it should behave. (allowNullable: false)

@vkarpov15
Copy link
Collaborator

This was fixed in v8.3.1 with #14504, looks like the same issue as #14445. Please upgrade to v8.3.1 for the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants