Error al usar hasMany en sequelize

tengo problemas con crear modelo con el ORM sequelize

const User=require('./user.model');  const Course = (sequelize, DataTypes) => {   const model = sequelize.define('course', {     id: {       type: DataTypes.UUID,       primaryKey: true,       defaultValue: DataTypes.UUIDV4,       allowNull: false     },     name: {       type: DataTypes.STRING,       allowNull: false     },        user: {         associate: models => {           Categories.hasMany(models.User);         }       }    });   return model; }  module.exports = Course; 

creo que es debido a que estoy haciendo mal la relacion de “tiene muchos, hasMany”, obtengo este error:

/home/ubuntu/Escritorio/Boot/hubman_demo/node_modules/sequelize/lib/model.js:994         throw new Error(`Unrecognized datatype for attribute "$  {this.name}.$  {name}"`);         ^  Error: Unrecognized datatype for attribute "course.user"     at rawAttributes._.mapValues (/home/ubuntu/Escritorio/Boot/hubman_demo/node_modules/sequelize/lib/model.js:994:15)     at /home/ubuntu/Escritorio/Boot/hubman_demo/node_modules/lodash/lodash.js:13402:38 

sequelize self association error Aliased associations must have unique aliases [migrated]

I’m using sequelize 4.32 and I was trying to write a self-association in one of the tables, I’m not sure if there is something else that I need to do to solve this relation, my goal is to get all the records in my table and include all the records associated with each one this is the error that I’m getting in the console:

You have used the alias adjucent_stands in two separate associations. Aliased associations must have unique aliases

below you’ll find my model:

module.exports = (sequelize, DataTypes) => {   const stands = sequelize.define('stands', {     id: {       type: DataTypes.INTEGER,       unique: true,       allowNull: false,       primaryKey: true,       autoIncrement: true,     },     name: {       type: DataTypes.STRING,       field: 'name',       unique: {         args: true,         msg: 'Name already exists ',       },     },     location: {       type: DataTypes.JSON,       field: 'location',     },     remote: {       type: DataTypes.BOOLEAN,       field: 'remote',       defaultValue: false,     },     created_at: {       type: DataTypes.DATE(3),       defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),     },     updated_at: {       type: DataTypes.DATE(3),       defaultValue: sequelize.literal('CURRENT_TIMESTAMP(3)'),     },   }, { freezeTableName: true, timestamps: true, underscored: true });    stands.associate = (models) => {     stands.hasMany(stands, { as: 'adjucent_stands' });   };    return stands; }; 

Como alterar o nome das três colunas padrões que o Sequelize gera?

O sequelize gera as colunas id, createdAt e updatedAt mesmo que eu não queira, isso é muito chato, porque eu gostaria que por exemplo, ID da tabela usuarios fosse “cd_usuario” e nao o nome ID propriamente dito, e createdAt e UpdatedAt fossem “dt_cad_sys” e “ult_dt_cad_sys” respectivamente. Gostaria de saber como alterar essa “configuração padrão” ou simplesmente impedir que o Sequelize crie qualquer coluna automaticamente.

não é necessário postar um trecho de código aqui para exemplificar melhor, penso.

No me crean relaciones con sequelize

estoy creando un servidor con expressjs y estoy utilizando como orm sequelize.

Adjunto código de ambos modelos.

noticia.js:

        const sequelize = require("sequelize");     const db = require("../models/db");     const Model = sequelize.Model;     const Categoria = require("./categoria").Categorias;     const Notificacion = require("./notificacion").Notificaciones;      class Noticias extends Model { }     Noticias.init(       {         id: {           type: sequelize.INTEGER,           primaryKey: true,           autoIncrement: true,           unique: true         },         titular: {           type: sequelize.STRING,           allowNull: false,           notEmpty: true,           validate: {             notEmpty: {               msg: "Debes de introducir un titular de noticia."             },             notNull: {               msg: "El valor introducido no puede ser nulo."             }           }         },         contenido: {           type: sequelize.STRING(65000),           allowNull: false,           notEmpty: true,           validate: {             notEmpty: {               msg: "Debes de introducir contenido para tu noticia."             },             notNull: {               msg: "El valor introducido no puede ser nulo."             }           }         },         image: {           type: sequelize.STRING,           allowNull: false,           notEmpty: true           //defaultValue: 'default'         },         categoria_id: {           type: sequelize.INTEGER         },       },       {         sequelize: db,         freezeTableName: true       }     );      Noticias.beforeCreate((noticia, options) => {       Notificacion.create({         titulo: "Nueva Noticia",         cuerpo: noticia.titular,         autor_id: noticia.autor_id       });     });      Noticias.associate = (models) => {       Noticias.hasOne(models.Categoria, {         foreignKey: "categoria_id",       });     };      module.exports = {       Noticias     }; 

categoria.js:

    const sequelize = require("sequelize"); const db = require("../models/db"); const Model = sequelize.Model; const Noticia = require("./noticia").Noticias; const Notificacion = require("./notificacion").Notificaciones;  class Categorias extends Model { } Categorias.init(   {     id: {       type: sequelize.INTEGER,       primaryKey: true,       autoIncrement: true,       unique: true     },     nombre: {       type: sequelize.STRING,       allowNull: false,       notEmpty: true,       validate: {         notEmpty: {           msg: "Debes de introducir un nombre de categoría."         },         notNull: {           msg: "El valor introducido no puede ser nulo."         }       }     },     image: {       type: sequelize.STRING,       allowNull: false,       notEmpty: true       //defaultValue: 'default'     }   },   {     sequelize: db,     freezeTableName: true   } );  Categorias.beforeCreate((categoria, options) => {   Notificacion.create({     titulo: "Nueva Categoría",     cuerpo: categoria.nombre   }); });  Categorias.associate = (models) => {   Categorias.hasMany(models.Noticia, { foreignKey: "id" }); };  module.exports = {   Categorias }; 

Lo que quiero conseguir es realizar la relación entre ambas tablas correctamente para hacer una consulta que me devuelva todos los campos de la noticia y además traer el nombre de la categoría a la que pertenece dicha noticia.

El mensaje de error es el siguiente:

{ SequelizeEagerLoadingError: Categorias is not associated to Noticias!     at Function._getIncludedAssociation (C:\PROYECTOS\SpicaProyect\node_modules\sequelize\lib\model.js:716:13)     at Function._validateIncludedElement (C:\PROYECTOS\SpicaProyect\node_modules\sequelize\lib\model.js:620:53)     at options.include.options.include.map.include (C:\PROYECTOS\SpicaProyect\node_modules\sequelize\lib\model.js:516:37)     at Array.map (<anonymous>)     at Function._validateIncludedElements (C:\PROYECTOS\SpicaProyect\node_modules\sequelize\lib\model.js:511:39)     at Promise.try.then.then (C:\PROYECTOS\SpicaProyect\node_modules\sequelize\lib\model.js:1715:14)     at tryCatcher (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\util.js:16:23)     at Promise._settlePromiseFromHandler (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\promise.js:512:31)     at Promise._settlePromise (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\promise.js:569:18)     at Promise._settlePromise0 (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\promise.js:614:10)     at Promise._settlePromises (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\promise.js:694:18)     at _drainQueueStep (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\async.js:138:12)     at _drainQueue (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\async.js:131:9)     at Async._drainQueues (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\async.js:147:5)     at Immediate.Async.drainQueues [as _onImmediate] (C:\PROYECTOS\SpicaProyect\node_modules\bluebird\js\release\async.js:17:14)     at runCallback (timers.js:763:18)     at tryOnImmediate (timers.js:734:5)     at processImmediate (timers.js:716:5) name: 'SequelizeEagerLoadingError' } 

He buscado varias soluciones por el foro y he probado el código que se utiliza en la documentación oficial de sequelize pero no funciona. Un saludo.

I just created a Store System using Electron, React, Material-UI, Redux, Redux-Saga, MySQL and Sequelize, and here is the result

This project is part of my personal portfolio, so, I’ll be happy if you could provide me any feedback about the project, code, structure or anything that you can report that could make me a better developer!

Also, you can use this Project as you wish, be for study, be for make improvements or earn money with it!

https://github.com/steniowagner/store-system

const whenShouldHelpCommunity = () => {     const when = 'always';      return when; } 

Sequelize Associantions

Possuo 2 models:

user features:

const DataTypes = require('sequelize'); const database = require('../config/dbconnection'); const user= require('./user');  const user_features = database.define('user_features', {     id: {       type: DataTypes.INTEGER(6),       allowNull: false,       primaryKey: true,       autoIncrement: true     },     user_id: {       type: DataTypes.INTEGER(6),       references: 'USERS',       referencesKey: 'user_id',       allowNull: true     },     {       text:{           type: "LONGBLOB",           allowNull: true       }     },     {        timestamps: false     });      user_features.belongsTo(user);     module.exports = user_features; 

users:

const DataTypes = require('sequelize'); const database = require('../config/dbconnection');  const users = database.define('users', {     id: {       type: DataTypes.INTEGER(6),       allowNull: false,       primaryKey: true,       autoIncrement: true     },     name {       type: DataTypes.STRING(45)     }  },  {    timestamps: false  });   module.exports = users; 

e no console mostra o seguinte erro:

Error: user_features.belongsTo called with something that's not a subclass of Sequelize.Model 

Preciso fazer a associação entre essas tabelas para na regra de negocio eu poder fazer um select no banco de dados e trazer essas informações.

Atualmente eu estou fazendo o select assim:

model.sequelize.query('SELECT NAME, TEXT FROM USERS LEFT JOIN USER_FEATURES ON USERS.ID = USER_FEATURES.USER_ID') 

mas quero padronizar o prejo e queria utilizar o ORM:

 getAll = (req, res, next) => model.findByPk(req.params.id,             {                 attributes: ['NAME', 'TEXT']                    })             .then((result) => {                 res.send(result);             })             .catch(error => console.log('repository getById error: ' + error)); 

Como poderia fazer essa associação?

Condicionais dentro do WHERE SEQUELIZE – Javascript – NodeJs

Estou aprendendo agora a utilizar o sequelize e durante a solução de um problema, irei precisar encontrar o menor id dentro de uma tabela porem utilizando uma condicional. É possível inserir condicionais dentro do where no sequelize?

let estacaoNormalGeradora = await Estacao.findOne({                 where: {                     tipo_estacao: 'NORMAL_GERADORA',                     bypass: false                 },                 attributes: ['id']             }); 

Gostaria de ter o retorno somente da primeira estação (menor id) e que esteja com bypass em false

Como utilizar o “LIKE” do sql no sequelize

ola estou desenvolvendo utilizando sequelize mas como é minha primeira vez utilizando esta ORM estou com algumas duvidas. Eu tenho o código abaixo para fazer um consulta no banco de dados através de um input tipo text porém estou utilizando o atributo no where que se refere ao igual e gostaria de um que seria o contenha ou seja verificar se alguma das informações no input de busca contem no campo username o meu codigo atual é este

User.findAll({ where: { US_USERNAME: req.query.search } }).then(users => {                             res.render('main/users', {                                 title: "Usuarios",                                 usuario: users,                             });                         });

Eu gostaria de trocar o igual do where por um like para verificar se a palavra consultada em req.query.search } contém no campo de username do meu banco e não se é igual. Resumindo quero trocar o igual do where por um like no sequelize

Comparar que una fechas en formato timestamptz, PostgreSQL, Sequelize

Estoy teniendo problemas al comparar dos fechas en timestamptz, tengo una tabla con un campo fecha de expiración y necesesito comparar, que una fecha no sea mayor a la de expiración que esta en la tabla, estoy usando Sequelize

let ahora = new Date(); function verificar (id, ahora) {  return modelo.findOne({   where: {     id   },   fecha_exp: {     [Op.gte]: ahora   }  }); } 

Les agradeceria su colaboración

How to keep all sequelize fieldnames refrenced in one place to increase code maintianability

I am struggling trying to figure out how to keep field names maintainable with sequelize. Right now I am thinking of doing the following, but it seems like there should be a better way: I will have my models and in a sub directory I will keep the shared field names (I will use my user model and my base model as an example):

  src ├── models     └── user.js     └── base.js     |     ├── field-names        └── user-fields.js 

In the user model I will have the following:

const BaseModel = require('./base'); const userFields  = require('./field-names/photo-fields');     class User extends BaseModel {         static init(DataTypes) {             return super.init(DataTypes, {                 userFields.username: {                     type: DataTypes.TEXT,                     allowNull: false,                     field: 'username',                 },             });         }     }; 

The base model I’m not worried about, but it extends Sequelze.Model and changes some settings (field formatting, default fields) to make it easier to work with PostgreSQL, and some other tools we use when exporting data from PostgreSQL. In the user-fields.js file I would have the following:

module.exports = {username:'username',} 

The motivation behind all of this is that if I have some other file that uses the user model and creates users I can do something like this:

const userFields  = require('./field-names/photo-fields'); //...some other code user.create({userFields.username:'my username'}); 

The benefit being that I can change username only in the fields file using my IDEs refactoring tool, and it will change throughout the codebase (e.g. to {nameOfUser: 'name-of-user}). However, since sequelize deals with creating the models and generating a lot of the code that way for you, I am wondering if I missed something, or if there is a way to source all fieldnames from some place that doesn’t require you to make a separate file to store them all. I didn’t see anything like this mentioned in the documentation, but it seems very limiting to either be stuck with whatever you first name a field of a model, or have to track down all the places you may have used that field name and change them.