简体   繁体   中英

Nodejs Sequelize Attributes Get data inside an object

I have a postgres database which look like this:

在此处输入图像描述

I want to query those data and return only some of it. Below is the function that I wrote.

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); } };

Here is the response from function above:

在此处输入图像描述

The problem is, I don't want to return all of the profil_penduduk object data, I just want to get the nama, alamat, and status_warga from it.

在此处输入图像描述

How can I achieve that? I tried to do like:

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

But it didn't work.

Best way to get the details of reference table to use include as

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,
    });
    ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM