乐闻世界logo
搜索文章和话题

How to use Sequelize in SailsJs

1个答案

1

1. Installing and Configuring Sequelize

First, ensure that Node.js and Sails.js are installed in your project before using Sequelize. Next, install Sequelize and the required database drivers via npm, such as PostgreSQL, MySQL, or SQLite.

bash
npm install sequelize npm install pg pg-hstore # For PostgreSQL example

2. Initializing Sequelize

Create a service in Sails.js to initialize Sequelize. Create a file named SequelizeService.js in the api/services directory with the following content:

javascript
const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'host', dialect: 'postgres', // Adjust based on the database type pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }); module.exports = sequelize;

This code initializes Sequelize and exports it as a module for use in other parts of your Sails.js application.

3. Creating Models

Create model files in the api/models directory. For example, create a file named User.js to define the user model:

javascript
const Sequelize = require('sequelize'); const sequelize = require('../services/SequelizeService'); const User = sequelize.define('user', { username: { type: Sequelize.STRING, allowNull: false }, email: { type: Sequelize.STRING, allowNull: false }, password: { type: Sequelize.STRING, allowNull: false } }); module.exports = User;

This defines a simple user model with fields for username, email, and password.

4. Using Models

You can use this model in api/controllers for database operations. For example, to create a user:

javascript
const User = require('../models/User'); module.exports = { async createUser(req, res) { try { const { username, email, password } = req.allParams(); const user = await User.create({ username, email, password }); return res.ok(user); } catch (error) { return res.serverError(error); } } };

5. Configuring Routes

Add routes in config/routes.js to call this controller method:

javascript
'POST /user': 'UserController.createUser',

This completes the basic setup for using Sequelize in Sails.js. You can extend these examples as needed for different models and controller methods. This process provides flexibility in integrating Sequelize into your Sails.js project while leveraging its powerful features, such as model associations and transaction handling.

2024年6月29日 12:07 回复

你的答案