I
I
Ivan Smirnov2020-07-22 22:35:36
Node.js
Ivan Smirnov, 2020-07-22 22:35:36

Why does sequelize return only one record and with wrong rate field?

Here are the models:
news:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const news = sequelize.define('news', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    title: DataTypes.STRING,
    slug: {
      type: DataTypes.STRING(64),
      unique: true
    },
    body: DataTypes.STRING,
    postedBy: DataTypes.INTEGER
  }, {});
  news.associate = function(models) {
    models.news.hasMany(models.news_ratings, {  
      as: 'rate',
      foreignKey: models.news_ratings.newsId
    })
  };
  return news;
};

news_ratings:
'use strict';
module.exports = (sequelize, DataTypes) => {
  const news_rating = sequelize.define('news_ratings', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    user: DataTypes.INTEGER,
    rating: DataTypes.INTEGER,
    newsId: DataTypes.INTEGER
  }, {});
  news_rating.associate = function(models) {
    models.news_ratings.belongsTo(models.news, {
      foreignKey: models.news.id
    })
  };
  return news_rating;
};

And controller:
router.get('/news/:from/:count', (req, res, next) => {
    if (Number.isInteger(Number(req.params.from)) && Number.isInteger(Number(req.params.count))) {
        models.news.findAll({
            offset: Number(req.params.from),
            limit: Number(req.params.count),
            include: [{
                as: 'rate',
                model: models.news_ratings,
                // required: true,
                attributes: [
                    [sequelize.fn('AVG', sequelize.col('rating')), 'rate']
                ]
            }]
        })
        .then(response => res.json(response))
        .catch(err => {
            console.error(err)

            res.status(500).end()
        }) 
    } else next()
})

news
5f18935e3fe85603381385.png
table: news_ratings table:
5f1894ea756c1180440322.png

if requested
/news/%any_digit%/1
then everything happens correctly, but if the last uri parameter is increased, then one record is displayed and the rate is incorrect

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question