【问题标题】:How can I read JSON data from a Sequelize search?如何从 Sequelize 搜索中读取 JSON 数据?
【发布时间】:2021-09-05 08:05:56
【问题描述】:

我正在开发一个车把应用,

router.get('/findBehavior/:student_id', async (req, res) => {
    console.log("---> req.params.student_id :" + JSON.stringify(req.params.student_id));

    const student = await Student.findByPk(req.params.student_id,{
        include: Behavior,
    });

    console.log("---> student :" + JSON.stringify(student));
    res.render('profile', {student, session: req.session});
});

但我无法读取进入 profile.handlebars 的 json 数据:

{
  "student_id": 1,
  "student_name": "Martina Hodson",
  "student_grade": 9,
  "Behaviors": [
    {
      "behavior_id": 1,
      "behavior_name": "No Problems",
      "StudentBehavior": {
        "student_id": 1,
        "behavior_id": 1
      }
    }
  ]
}

我正在尝试这段代码,但它不起作用...

{{student.Behaviors.[0].['behavior_id']}}

我得到了回应

[object SequelizeInstance:Behavior]

如何获取学生的姓名和学生的行为?

【问题讨论】:

    标签: json express sequelize.js


    【解决方案1】:

    问题不是我试图读取 JSON 的方式。

    在传递到把手页面之前,需要“清理”响应搜索的对象。

    我使用这段代码使对象变得简单:

    const student = dbStudentData.get({plain: true});
    

    你可以看到它是如何被其余代码包围的:

    router.get('/findBehavior/:student_id', async (req, res) => {
        console.log("---> req.params.student_id :" + JSON.stringify(req.params.student_id));
    
        const dbStudentData = await Student.findByPk(req.params.student_id, {
            include: Behavior,
        });
    
        // HERE --------------------------------------------------------
        const student = dbStudentData.get({plain: true});
        
        console.log("---> student :" + JSON.stringify(student));
        res.render('profile', {student, session: req.session});
    });
    

    由于只有一行数据,当多行数据时,不需要map函数来制作简单的整组数据。

    【讨论】:

      猜你喜欢
      • 2012-09-18
      • 1970-01-01
      • 2018-07-24
      • 2022-11-08
      • 1970-01-01
      • 2016-04-26
      • 2020-08-14
      • 2016-10-18
      • 1970-01-01
      相关资源
      最近更新 更多