This is my user.js function. How do I create an instance of it in another file? I understand that this structure is a function that contains a class that contains functions inside it.
user.js
'use strict';
const {Sequelize} = require('sequelize');
const {
Model
} = require('sequelize');
//This is a function that contains a class that contains functions
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static init(sequelize) {
super.init(
{
name: Sequelize.STRING,
},
{
sequelize,
});
this.addHook('beforeSave', async (user) => {
return user.id = uuid();
});
return this;
}
static associate(models) {
// define association here
User.hasMany(UserRole,
{
foreignKey: {
field:'UserId',
allowNull: false,
},
});
}
}
User.init({
Id: DataTypes.UUID,
Name: DataTypes.STRING,
UserName: DataTypes.STRING,
Email: DataTypes.STRING,
Password: DataTypes.STRING,
PhoneNumber: DataTypes.STRING,
MobileNumber: DataTypes.STRING,
DateOfBirth: DataTypes.DATE,
LockoutEnabled: DataTypes.BOOLEAN,
LockoutEnd: DataTypes.DATE
}, {
sequelize,
modelName: 'User',
});
return User;
};
In another file I have tried:
const {Sequelize, DataTypes} = require('sequelize');
const {sequelize} = require('../../database/connect');
const {userModel} = require('../../models/user');
function GetAll(UserName, Email){
var option = new userModel;
var option2 = new userModel(sequelize, DataTypes);
return "1";
}
But both give me this error:
TypeError: userModel is not a constructor
at Object.GetAll (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectdatauserdatauserdata.js:8:16)
at GetAll (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectareasdirectorycontrollersusercontroller.js:6:27)
at Layer.handle [as handle_request] (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:341:12)
at next (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:275:10)
at Function.handle (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:174:3)
EDIT:
If I remove new from them, I get the error: userModel is not a function.