Search code examples
javascriptnode.jssequelize.jskoa

Sequelize create not a function?


I am trying to use model.create and it's saying that model.create is not a function. I googled around and couldn't seem to find any rmesolutions. Please note that I'm using es6 imports / exports in node via babel.

model.js

'use strict';
export default (sequelize, DataTypes) => {
  let attachments = sequelize.define('attachments', {
    type: DataTypes.STRING,
    category: DataTypes.STRING,
    value: DataTypes.STRING,
  }, {});
  attachments.associate = (models) => {
  };
  return attachments;
};

controller

import attachments from '../../../models/attachments'
import to_attachments from '../../../models/to_attachments'
import AWSService from '../../utils/awsS3Api'

export async function createPhoto(ctx) {

 ... 

  try {
      let attachment = await attachments.create({
        type: 'image',
        category: imageCategory,
        value: data.location
      });
..etc

What am I doing wrong?


Solution

  • If you declare model via function:

    export default (sequelize, DataTypes) => {
      ...
    };
    

    Then you should import it with sequelize.import

    const Attachment = sequelize.import('../../../models/attachments')
    
    export async function createPhoto(ctx) {
      const attachment = await Attachment.create({
        type: 'image',
        category: imageCategory,
        value: data.location
      });
    }
    

    P.S. Some recommendations

    1) Name model variables with capital letter you deal with static classes.

    const user = await User.findById(123)
    const users = await User.findAll({where: {id: [1,2,3]}})
    

    2) Singular not Users but User.