【问题标题】:Object property is filled when shown but undefined when accessed. Nodejs Sequelize对象属性在显示时填充,但在访问时未定义。 Nodejs 续集
【发布时间】:2021-03-08 07:54:51
【问题描述】:

我正在执行这个原始 sql 查询

SELECT postId, users.id as userId,users.firstName,users.lastName,users.avatar,COUNT(postId) as 
numOfLikes,body
FROM posts
INNER JOIN likes ON likes.postId = posts.id
INNER JOIN users ON users.id = posts.userId
GROUP BY postId
ORDER BY postId DESC

通过nodeJs sequelize ORM

 Posts.findAll({
                attributes: ['id','body','createdAt', [db.fn('count', db.col('likes.postId')), 'numOfLikes']],
                include: [{ attributes: [], model: Likes,required:true, },{model:Users,required:true}],
                group: ['id'],
                order: [['id', 'DESC']]       
            })

我收到了应有的所有内容,但无法访问 numOfLikes 对象属性(未定义)

{
 "id": 18,
  "body": "This show was organized.",
  "createdAt": "2021-03-06T23:55:44.000Z",
  "numOfLikes": 5,
  "user": {
  "id": 73,
  "firstName": "Paolo",
  "lastName": "Jovovic",
  "email": "dzonnna@gmail.com",
  "email_verified": "1",
  "password": "$2b$10$6fLwPfuLP8Jfp7em0iqBm.YhznDut8AWOmUPynqecfd9YMvZBMaXq",
  "google_id": null,
  "avatar": "1_aZF6_EToO4T3ZeHXfgF-Vg.png",
  "role": "0",
  "createdAt": "2021-02-28T22:30:42.000Z",
  "updatedAt": "2021-03-01T23:59:21.000Z"
  }
  }

【问题讨论】:

  • 那个 GROUP BY 无效。您通常 GROUP BY 与您选择的列相同 - 除了那些作为设置函数的参数的列。
  • @jarlh 我将 id 更改为 postId 仍然是同样的问题
  • 你需要添加显示未定义的代码

标签: sql node.js sequelize.js


【解决方案1】:
        Posts.findAll({
            attributes: ['id', 'body', 'createdAt', [db.fn('count', db.col('likes.postId')), 'numOfLikes']],
            include: [{ attributes: [], model: Likes, required: true, }, { model: Users, required: true }],
            group: ['id'],
            order: [['id', 'DESC']]
        }).then(postList => {
            postList = JSON.parse(JSON.stringify(postList)) // This is important
            postList.forEach(post => {
                // access post
                console.log(post, post.users)
            });
        })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多