Locked video

Please purchase the course to watch this video.

Buy Now

Type safety

Allow null

Summary

By default, Waterline does not allow null values for attributes of type string, number, or boolean. However, in some cases, you may need to explicitly allow null to indicate the absence of a value. This can be done using the allowNull: true property. This lesson demonstrates how to enable null values for specific attributes while noting that allowNull does not apply to primary keys, associations, or attributes of type JSON and ref, since those already support null by default.

Transcript

By default, Waterline does not allow null values for string, number, and boolean attributes. If you try to pass null to one of these types, Waterline will reject it.

But what if, in your business logic, null is meaningful? For example, you might want firstName to be optional and allow null, while lastName is required.

To achieve this, you need to explicitly tell Waterline that the attribute can accept null using the allowNull property.

Let’s see how to do this in code. In our model definition, we modify firstName like this:

firstName: {
  type: 'string',
  allowNull: true
},
lastName: {
  type: 'string',
  required: true
}

Now, if we create a user and pass null for firstName:

await User.create({ firstName: null, lastName: 'Goodfrey' }).fetch();

Waterline allows the null value, and if we fetch the created user, we’ll see:

{
  "firstName": null,
  "lastName": "Goodfrey"
}

This works for string, number, and boolean attributes. For example, if we want to allow null for age and isAdmin, we define:

age: {
  type: 'number',
  allowNull: true
},

isAdmin: {
  type: 'boolean',
  allowNull: true
}

However, allowNull does not apply to:

  • JSON and ref types (since null is already a valid value for them)

  • Primary keys (since they must always have a unique identifier)

  • Waterline associations (which we’ll cover later)

Using allowNull lets you explicitly define which attributes can be null, ensuring your data structure aligns with your business logic.

Full Course

$
34.99

USD

plus local taxes
Buy Now