【问题标题】:Nodejs Sequelize Attributes Get data inside an objectNodejs Sequelize Attributes 获取对象内部的数据
【发布时间】:2021-12-01 15:16:01
【问题描述】:

我有一个如下所示的 postgres 数据库:

我想查询这些数据并只返回其中的一部分。下面是我写的函数。

citizenController.js

exports.getAllCitizen = async (req, res) => {
  const { page, size } = req.query;
  //Check if theres a NIK filter
  const nik = req.query.nik;
  const condition = nik ? { nik: { [Op.iLike]: `%${nik}%` } } : null;

  //Pagination
  const { limit, offset } = getPagination(page, size);

  try {
    const response = await Penduduk.findAndCountAll({
      where: condition,
      attributes: ["id", "nik", "profil_penduduk"],
      limit,
      offset,
    });
    const data = getPagingData(response, page, limit);

    return res.status(200).send(data);
  } catch (err) {
    console.log(err);
  }
};

这是上面函数的响应:

问题是,我不想返回所有的 profil_penduduk 对象数据,我只想从中获取 nama 、 alamat 和 status_warga

我怎样才能做到这一点?我试着这样做:

attributes: ["id", "nik", "profil_penduduk.nama","profil_penduduk.alamat","profil_penduduk.status_warga"]

但是没有用。

【问题讨论】:

    标签: javascript node.js postgresql sequelize.js


    【解决方案1】:

    获取参考表详细信息的最佳方法是使用include作为

    const response = await Penduduk.findAndCountAll({
          where: condition,
          attributes: ["id", "nik"],
          include: [
            {
              model: profil_penduduk, // name of reference table
              attributes: ['nama' , 'alamat', 'status_warga'],
            }
          ],
          limit,
          offset,
        });
        ```
    

    【讨论】:

    • 您好,感谢您的退房。但问题是profil_penduduk 不是被引用的able,它是citizen 表中的一列。
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 2012-02-06
    • 2019-11-10
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多