sequelize / sequelize/sequelize

Is there any way to omit null values?

Open
#11,013 8 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

existing workaround question status: understood type: feature
Dominant language
TypeScript
Stars
30.4k
Forks
4.3k
Avg merge
1d 6h
Merged PRs (30d)
68

Description

What are you doing?

I have a model defined as bellow:

const Scene = sequelize.define(
  'scene',
  {
    sceneId: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
    owner: { type: Sequelize.STRING, allowNull: false },
    name: Sequelize.STRING,
    description: Sequelize.STRING,
    width: Sequelize.INTEGER,
    height: Sequelize.INTEGER
  }
)

When I query one instance use Scene.findOne and send back to express:

const scene = Scene.findOne({...})
res.json(scene)

I get a scene like this:

{
  "sceneId": "12356",
  "owner": "sam",
  "name": null,
  "description": null,
  "width": null,
  "height": null
}

As null would break our webapp, I would like to have this:

{
  "sceneId": "12356",
  "owner": "sam"
}

Is there any way to omit these null values when calling scene.toJSON()?

To Reproduce
Steps to reproduce the behavior:

  1. Define models X, Y, ...
  2. Run the following
  3. See error

What do you expect to happen?

I wanted Foo!

What is actually happening?

But the output was bar!

Output, either JSON or SQL

Environment

Dialect:

  • mysql
  • postgres
  • sqlite
  • mssql
  • any
    Dialect library version: XXX
    Database version: XXX
    Sequelize version: XXX
    Node Version: XXX
    OS: XXX
    If TypeScript related: TypeScript version: XXX
    Tested with latest release:
  • No
  • Yes, specify that version:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Sequelize model defined in the issue and trace the result from Scene.findOne through scene.toJSON() before it is passed to res.json. Check the existing serialization behavior and tests, if present; the work is done when a supported approach or behavior omits null-valued attributes while retaining populated fields.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend, databases
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.