调用sequelize findAll方法后,setDataValue不是函数

时间:2019-11-01 14:34:19

标签: javascript node.js sequelize.js

我希望在sequelize findAll方法之后创建一个新属性。

使用此方法

setDataValue

即时通讯

  

setDataValue不是函数

https://sequelize.org/master/class/lib/model.js~Model.html#instance-method-setDataValue

enter image description here

post.controller.js

 getPosts: async (req: any, res: Response) => {
    await models.Post.findAll({
      include: [
        { model: models.User, as: "author", attributes: ["username"] },
        { model: models.Likes }
      ],
      order: [["createdAt", "DESC"]],
      limit: 6
    }).then(posts => {
      posts.setDataValue('test', 'hoot')
      res.json(posts);
    });
  },

1 个答案:

答案 0 :(得分:1)

在您的示例中,posts是一个数组,而不是单个对象,因此无法在其上调用setDataValue()。如果您想要单个结果,请使用findOne()findByPk()

遍历数组以访问返回访问权setDataValue()的每个实例。或者在查询中使用raw: true返回可以设置键的原始JSON对象,如果要以JSON形式返回,则性能更高。

由于您使用的是异步/等待,因此您也应该避免使用ableable。请尝试以下操作:

getPosts: async (req: any, res: Response) => {
  // use async/await here
  const posts = await models.Post.findAll({
    include: [
      { model: models.User, as: "author", attributes: ["username"] },
      { model: models.Likes }
    ],
    order: [["createdAt", "DESC"]],
    limit: 6,
    // uncomment this line to return raw JSON objects instead of Model Instances
    // raw: true,
  });

  // loop over each post in the array and convert t
  posts.forEach((post) => post.setDataValue('test', 'hoot'));

  // return result
  // note that you probably want to call post.toJSON() 
  // or add raw: true to your query
  return res.json(posts);
},