How to get model from sequelize.model after use sequelize-cli - node.js

I use sequelize-cli to auto generate code for model Student:
module.exports = (sequelize, DataTypes) => {
var _stu = sequelize.define('stu', {
name: DataTypes.STRING,
password: DataTypes.STRING,
gender: DataTypes.INTEGER,
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return _stu
};
My question are
How to get model named stu? As the sequelize is defined in function signature.
When sequelize model:generate,sequelize read config in config.json,where dbname,passowrd are specified.
How the sequelize in the function signature knows database connection config,say,name,password,etc as I don't specify in this js file.

Answer for question 1:
"sequelize.import" will do this job.
Try this code:
const Sequelize = require('sequelize')
const sequelize = new Sequelize(...)
const stu = sequelize.import('./models/stu')
stu.findAll.then(...)

When you generate models via the CLI, it creates a handy models/index.js file that handles passing in a Sequelize instance for you. You can simply require cherry picked, existing models via ES6 destructuring like this:
var { stu } = require("./models");
stu.findAll().then(...);
Alternatively, you could require them all at once, and then access specific models as needed:
var models = require("./models");
models.stu.findAll().then(...);

The way i make it works was importing model with the require() function and then call it with required parameters.
Explanation
By require function you will get another function that returns your model.
module.exports = (sequelize, DataTypes) => {
const stu = sequelize.define('stu', {
// ...database fields
}, {});
stu.associate = function(models) {
// associations can be defined here
};
return sty;
} // note that module.exports is a function
Now, this function requires the initialized sequelize object and a DataTypes object, so you just have to pass the instance of sequelize and Sequelize.DataTypes and then it will return your model, example:
const Sequelize = require('sequelize');
const sequelize = new Sequelize(...);
const Stu = require('./models/stu')(sequelize, Sequelize.DataTypes);
Finally you can get your database rows with Stu.findAll().
Hope this can help you.

Related

Sequelize write model separate file with intellisense

This is my code for the model
const {DataTypes} = require('sequelize');
module.exports = (sequelize) => {
const Category = sequelize.define(
"category",
{
name:{
type:DataTypes.STRING,
allowNull: false,
},
color:{
type:DataTypes.STRING,
defaultValue: 'red'
}
},
);
return Category;
};
and in the index.js (main Sequelize config)
const db = {}
db.Sequelize = Sequelize
db.sequelize = sequelize
db.notes = require('./note')(sequelize)
db.categories = require('./category')(sequelize)
My problem is that the sequelize object in the model is as a parameter and I have no intellisense for the options of the object.
How can I set the model in separate file and get the intellisense
There are 3 possible ways forward I can see:
Export sequelize instance from the index.js instead of using as a function parameter
Utilize Sequelize's class Model definition
Use Typescript

Sequelize doesn't read the new modelname after I do refactor (remove s in end modelname)

I've a backend app built in Express with Sequelize ORM.
Here is my code;
user.js (model)
'use strict';
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
username: DataTypes.STRING,
}, {
// tableName: 'user'
});
user.associate = function(models) {
// associations can be defined here
};
return user;
};
user.js (controller):
const User = require('../models').user;
module.exports = {
getUser: function (req, res) {
User.findAll().then(value => {
res.json(value);
})
}
}
When I start the project, it return error Unhandled rejection SequelizeDatabaseError: relation "users" does not exist. As you can see my code above, I've set the model as user not users, and the table in db also user not users. It's only work fine if I add the tableName: 'user' in the model file.
NOTE: By the default, when I do create model with sequelize, the file name and model define is users, but I refactor file name and define inside model into user
Why does this happen?
This is default behavior - Sequelize automatically transforms model name to plural. In order to disable that you should freeze table name in model definition (or just set table name explicitly like you are actually doing):
freezeTableName: true,

Sequelize build is not a function when model is created from migration

This is my model which is create from sequelize cli: (it describes an user in User.js)
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
username: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
When I try to create it in my script file, I get this following error:
User.build is not a function
Here's how I call the build method:
const User = require('../models/User');
User.build({
username: message["name"],
}).save();
In your case it returns a function not constructor
you have to pass sequelize and DataTypes while importing it
const User= require('../models/User')(sequelize, DataTypes);
Hope it'll work for you
You need to require model from "model/index"
so change this
const User = require('../models/User');
to this
const {User} = require('../models/index');
refer to this answer

How to deal with require-loops?

I have two models defined like this:
user.js
var sequelize = require('../database.js').sequelize,
Sequelize = require('../database.js').Sequelize,
userAttributes = require('./userAttributes.js');
User = sequelize.define('user', {},{
classMethods: {
createRider: function(params) {
var reqs = ['name', 'phone', 'fbprofile'],
values = [],
newUser;
reqs.forEach((req) => {
var value = params[req];
});
//Here I want to use the userAttributes-object.
return newUser;
}
}
});
module.exports = User;
userAttributes.js
var sequelize = require('../database.js').sequelize,
Sequelize = require('../database.js').Sequelize,
User = require('./user.js');
UserAttribute = sequelize.define('userAttributes', {
name: Sequelize.STRING,
value: Sequelize.STRING,
});
UserAttribute.belongsTo(User);
module.exports = UserAttribute;
in user User.addRider I want to add some records to UserAttributes, so I want to inclued that model in user. In userAttributes, I need to require Users to define it as a belongsTo. This doesn't seem to work. How can I solve this?
You can use a single file which imports all models and associates them after all models have been imported. This way, you do not need any circular references.
The second most popular answer in this question describes how to do it: How to organize a node app that uses sequelize?.

Sequelize: Require vs Import

In the documentation for sequlize they use the import function like so
// in your server file - e.g. app.js
var Project = sequelize.import(__dirname + "/path/to/models/project")
// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
}
However, what would be so wrong with this?
// in your server file - e.g. app.js
var Project = require(__dirname + "/path/to/models/project")
// The model definition is done in /path/to/models/project.js
var Project = sequelize.define("Project", {
name: Sequelize.STRING,
description: Sequelize.TEXT
});
module.exports = Project
Well, as you can see your model definition needs two things:
Sequelize or DataTypes
sequelize
In your first example when using sequelize.import('something'); it is similar to use require('something')(this, Sequelize); (this being the sequelize instance)
Both are necessary to initialize your model, but the important thing to understand is: One of these is a classtype so it's global, the other one is an instance and has to be created with your connection parameters.
So if you do this:
var Project = sequelize.define("Project", {
name: Sequelize.STRING,
description: Sequelize.TEXT
});
module.exports = Project
Where does sequelize come from? It has to be instantiated and passed somehow.
Here is an example with require instead of import:
// /path/to/app.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize(/* ... */);
var Project = require('/path/to/models/project')(sequelize, Sequelize);
// /path/to/models/project.js
module.exports = function (sequelize, DataTypes) {
sequelize.define("Project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
});
};
module.exports = Project
You could even change it so you wouldn't have to pass Sequelize by requiring it in the model itself, but you would still need to create a sequelize instance prior to define the model.
sequelize.import is deprecated as of sequelize 6
As mentioned at https://sequelize.org/master/manual/models-definition.html
Deprecated: sequelize.import
Note: You should not use sequelize.import. Please just use require instead.
So you should just port:
// index.js
const sequelize = new Sequelize(...)
const User = sequelize.import('./user')
// user.js
module.exports = (sequelize, DataTypes) => {
// Define User.
return User;
}
to:
// index.js
const sequelize = new Sequelize(...)
const User = require('./user')(sequelize)
// user.js
const { DataTypes } = require('sequelize')
module.exports = (sequelize) => {
// Define User.
return User;
}

Resources