Skip to content

update method tries to insert null when receiving undefined  #7056

Closed

Description

@jony89

What you are doing?

I map some request to Sequelize model :

        var model = {
            title: req.body.title,
            description: req.body.description
        };
        models.job.update(model, {..}).then(() => {})

let say that req.body.title is undefined and req.body.description has value.
In the model, title cant be null.
For some reason sequelize tries to insert null to the title although it is undefined, resulting in getting the following error :

err.stack SequelizeValidationError: notNull Violation: title cannot be null

this happens probably because model.hasOwnProperty('title') returns true, but yet, model.title is undefined and not null

What do you expect to happen?

I think that in that case, when a field is undefined, Sequelize should not try to insert null into it (the title field) and just ignore it

What is actually happening?

i get an error :

err.stack SequelizeValidationError: notNull Violation: title cannot be null

I think we should insert null only when someone specifically specify that this field is null.

Dialect: mysql
__Database version: 5.7.9
__Sequelize version: 3.28.0

Activity

  1. jony89 commented on Jan 24, 2017

    @jony89
    Author

    if i add :

      //remove undefined values
      Object.keys(values).forEach(function(key) {
        if (values[key] === undefined) {
          delete values[key];
        }
      }); 

    at ./lib/models.js after the comment :

    // Remove values that are not in the options.fields

    it works well, is this a possible solution ? should i create a PR?

  2. jony89 commented on Jan 30, 2017

    @jony89
    Author

    I've done few more testing and I found out that if the field allowed to have nulls, and i try to update with value undefined it actually skips it as desired.

    This actually supports my claim.. but it gives a different approach, maybe the problem is only with the validation ?

    If it is skipped, then why the validation checks for undefined as well : (file ./lib/instance-validator.js)

      if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
        error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value);
        this.errors.push(error);
      }

    could be

      if (rawAttribute.allowNull === false && value === null) {
        error = new sequelizeError.ValidationErrorItem(field + ' cannot be null', 'notNull Violation', field, value);
        this.errors.push(error);
      }

    further more, if i remove that validation, everything works as magic. sequelize doesnt try to insert null/undefined to the field and just skips it.

    so this issue is relevant only for not null fields. for others it works correctly.

  3. agalazis commented on Mar 14, 2017

    @agalazis

    that's true the only way to keep a value is to reinsert this sounds weird for an update especially for people who are used to update just the field they want . @mickhansen your input is appreciated.

  4. jony89 commented on May 30, 2017

    @jony89
    Author

    reproduced on sequelize v4 as well

  5. stale commented on Jul 29, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  6. jony89 commented on Jul 31, 2017

    @jony89
    Author

    this issue still need to be fixed. @mickhansen

  7. jony89 commented on Sep 30, 2017

    @jony89
    Author

    please reopen this, still need to be resolved.

  8. added
    type: bug
    on Sep 30, 2017
  9. sushantdhiman commented on Sep 30, 2017

    @sushantdhiman
    Contributor

    I assume can be reproduced on master

  10. jony89 commented on Sep 30, 2017

    @jony89
    Author

    Didn't retest it for a while, but yeah

  11. gabegorelick commented on Oct 17, 2017

    @gabegorelick
    Contributor

    This behavior is fairly consistent throughout Sequelize; e.g.

    Model.findAll({where: {foo: undefined}});

    will run SELECT ... WHERE foo IS NULL. I personally find this inconvenient as it means I need to remove undefined values from my where options, but if that's the decision Sequelize has made then present-but-undefined values should be treated as NULL everywhere. Otherwise, it would probably require a major version bump to change this behavior.

  12. jony89 commented on Oct 23, 2017

    @jony89
    Author

    @gabegorelick , that is not correct.

    As I shown above, there is different behaviour between nullable props and non-nullable props.

    I've done few more testing and I found out that if the field allowed to have nulls, and i try to update with value undefined it actually skips it as desired.

    This actually supports my claim..

  13. millermatt commented on Feb 23, 2018

    @millermatt

    Until this is fixed there is no way to update fields in a record without also setting all of the non-null field values, even if those are not changing.

  14. writebeat commented on May 29, 2018

    @writebeat

    This is still an issue on v4

  15. writebeat commented on May 29, 2018

    @writebeat

    Workaround is to set the fields option on the update function to Object.keys(req.body), worked for me, at least.

  16. gabegorelick commented on Jun 20, 2018

    @gabegorelick
    Contributor

    May be resolved by #9548.

  17. Alexsey commented on Jun 20, 2018

    @Alexsey
    Contributor

    No, it would not be resolved with #9548 because that one is only about undefined in where and here we have undefined in update object

  18. jony89 commented on Jun 21, 2018

    @jony89
    Author

    I've created a PR for this a while ago : #7167
    I'm pretty sure this is the correct solution, yet it was for v3 and the tests did not completely pass, need to give it some more time. I'll try to redo it this weekend.

  19. 1valdis commented on Sep 16, 2018

    @1valdis

    This is still an issue for me on v4.38.1. When we'd expect a fix?

  20. jony89 commented on Sep 16, 2018

    @jony89
    Author

    Can u share some code ? This should be fixed. it is tested manual+unit tests.

  21. 1valdis commented on Sep 16, 2018

    @1valdis

    Here you go. I have a User model with field 'name' on it:

    module.exports = (sequelize, types) => {
      const User = sequelize.define(
        'user',
        {
          // some fields...
          name: {
            type: types.STRING,
            allowNull: false,
            validate: {
              notEmpty: {
                msg: 'Name cannot be empty'
              }
            }
          },
          // some other fields...
        }, /* some options... */
      )
    
      return User
    }

    I import it to Sequelize. I have an api route to edit a user. It looks like this:

    exports.editMe = async (req, res) => {
        const user = await User.findById(/* ... */)
        console.log(user.get()) // {... , name: 'Kek!', ...}
        // assume that req.body is empty object here
        req.body.name = undefined
        // if I uncomment next line, it works as expected, not trying to insert null
        // delete req.body.name
        console.log(req.body) // {name: undefined}
        await user.update(req.body) // SequelizeValidationError: notNull Violation: user.name cannot be null
    }
  22. jony89 commented on Sep 16, 2018

    @jony89
    Author

    Yeah that's the case.

    I am sorry but it seems it was merged only to master (version > 5)

    I asked to merged it to v3 as well and got negative answer :\

    You can find the PR here #9587

    So either upgrade or can also use (as i mentioned be4)

    if (value) { model.val = value; } 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions