These are chat archives for NodejsRUS/chat

7th
Oct 2017
Ilia Pavlenkov
@dortonway
Oct 07 2017 11:00
всем привет )

кто-нибудь знает, почему если я пишу в контроллере:

  const books = await ctx.models.Book.findAll({
    include: [
      {
        model: ctx.models.Author,
        attributes: ['name'],
        as: 'Authors',
      },
    ],
  });

  const bs= books.map(book => {
    book.authors = R.compose(R.join(', '), R.pluck('name'), R.pluck('dataValues'))(
      book.Authors,
    );

    return book;
  });

то всё работает, а если в модели:

class Book extends Sequelize.Model {
  static associate({ Author, Section, BookAuthor }) {
    Book.belongsToMany(Author, { through: BookAuthor });
    Book.hasMany(BookAuthor, { onDelete: 'cascade' });
    Book.hasMany(Section, { onDelete: 'cascade' });
  }

  static async booksInfo() {
    const books = await Book.findAll({
      include: [
        {
          model: Author,
          attributes: ['name'],
          as: 'Authors',
        },
      ],
    });

    return books.map(book => {
      book.authors = R.compose(R.join(', '), R.pluck('name'), R.pluck('dataValues'))(
        book.Authors,
      );

      return book;
    });
  }
}

const schema = {
  name: {
    type: Sequelize.STRING,
  },
};

то нет?

если в модели, то выдаёт:
[nodemon] 1.12.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node --inspect .`
Debugger listening on ws://127.0.0.1:9229/5f7d23e7-831d-4954-ab18-7584427bf94d
For help see https://nodejs.org/en/docs/inspector
Listening on 127.0.0.1:4000

  TypeError: self._expandAttributes is not a function
      at Function._conformOptions (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:189:12)
      at Function._conformInclude (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:255:12)
      at options.include.options.include.map.include (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:204:59)
      at Array.map (native)
      at Function._conformOptions (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:204:39)
      at Promise.try.then (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:1515:12)
      at runCallback (timers.js:800:20)
      at tryOnImmediate (timers.js:762:5)
      at processImmediate [as _immediateCallback] (timers.js:733:5)
  From previous event:
      at Function.findAll (/databank/mega/development/js/readdis/node_modules/sequelize/lib/model.js:1514:8)
      at Function.booksInfo (/databank/mega/development/js/readdis/models/Book.js:13:30)
      at module.exports.Router.get (/databank/mega/development/js/readdis/middlewares/routers/home.js:33:63)
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-router/node_modules/koa-compose/index.js:44:32)
      at next (/databank/mega/development/js/readdis/node_modules/koa-router/node_modules/koa-compose/index.js:45:18)
      at /databank/mega/development/js/readdis/node_modules/koa-router/lib/router.js:345:16
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-router/node_modules/koa-compose/index.js:44:32)
      at /databank/mega/development/js/readdis/node_modules/koa-router/node_modules/koa-compose/index.js:36:12
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-router/lib/router.js:350:31)
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-compose/index.js:42:32)
      at /databank/mega/development/js/readdis/node_modules/koa-compose/index.js:34:12
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-compose/index.js:42:32)
      at next (/databank/mega/development/js/readdis/node_modules/koa-compose/index.js:43:18)
      at app.use (/databank/mega/development/js/readdis/index.js:26:10)
      at dispatch (/databank/mega/development/js/readdis/node_modules/koa-compose/index.js:42:32)
      at next (/databank/mega/development/js/readdis/node_modules/koa-compose/index.js:43:18)
      at bodyParser (/databank/mega/development/js/readdis/node_modules/koa-bodyparser/index.js:86:11)
      at <anonymous>
Ilia Pavlenkov
@dortonway
Oct 07 2017 11:05
вот так вызываю: await ctx.render('home', { booksInfo: await ctx.models.Book.booksInfo() });
Ilia Pavlenkov
@dortonway
Oct 07 2017 11:28
в конце каждого файла моделей пишу: module.exports = sequelize => Book.init(schema, { sequelize });
так загружаю модели:
const path = require('path');
const Sequelize = require('sequelize');
const { DB } = require('../config');
const { getDirFileNames } = require('../utils');

const sequelize = new Sequelize(DB, { logging: false });
const models = {};

getDirFileNames(__dirname).forEach(file => {
  const model = sequelize.import(path.join(__dirname, file));
  models[model.name] = model;
});

Object.keys(models).forEach(modelName => {
  if ('associate' in models[modelName]) {
    models[modelName].associate(models);
  }
});

module.exports = {
  sequelize,
  models,
};
если в модели в Include указать не 'Author' и не Author, который зареквайрен вверху файла, а сделать реквайр по месту, то почему-то работает:
    const books = await Book.findAll({
      include: [
        {
          model: require('.').models.Author,
          attributes: ['name'],
          as: 'Authors',
        },
      ],
    });
если передать модель Author из контроллера, то тоже работает
т.е. есть ощущение, что не работает при импорте модели вверху файла из-за circular dependency, но почему тогда работает, если реквайрить в статическом методе, а не вверху файла?