Locked video

Please purchase the course to watch this video.

Buy Now

Waterline models

Specifying table name

Summary

In Sails.js, the table name in the database corresponds to the lowercase version of the model name by default (e.g., Useruser).

This is referred to as the model identity in Waterline. However, if you prefer pluralized table names (e.g., users, products), you can customize this by adding a tableName property at the top level of your model definition.

This overrides the default behavior, allowing you to specify the exact table name to be used in the database. After updating, running sails lift will create or update the table accordingly.

Transcript

So, you might have noticed that for our table in the database, the name of the table corresponds to the lowercase version of the model name. This is what we call the model identity in Waterline. Essentially, the lowercase version of the model name (or the model file name) becomes the table name in the physical database.

For example, if we look at the database, you’ll see a table named user, which matches the model name User.

Now, what if you prefer pluralized table names? For instance, instead of user, you’d like users, or instead of product, you’d like products. To achieve this, you can override the default table name by specifying a tableName property at the top level of your model definition.

Here’s how you do it:

// In api/models/User.js
module.exports = {
  tableName: 'users', // Custom table name
  attributes: {
    // Your attributes here
  }
};

By adding tableName: 'users', you’re instructing Sails and Waterline to use users as the table name instead of the default user.

Let’s see this in action. After updating the model, run sails lift. If you check the database, you’ll notice a new table named users has been created. You can then delete or drop the old user table if needed.

From this point forward, your Sails app will use the users table for all operations. For example, inserting new records will now go into the users table.

Key Takeaways:

  1. By default, table names match the lowercase version of the model name (model identity).

  2. Use the tableName property to customize the table name (e.g., pluralized names).

  3. After updating, run sails lift to apply changes and ensure the new table is used.

Full Course

$
34.99

USD

plus local taxes
Buy Now