Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

387
Visualizações
Sequelize include even if it's null

I am using Sequelize express with Node.js as the backend, some data from my sequelize I need to include to another table but some of these data is null so the whole result I’m getting is null.

Question: how can I return some data if data it's available and return the other null if not data is there

router.get("/scheduled/:id", function(req, res, next) {

    models.Order.findOne({

        where: {
            id: req.params.id
        },
        attributes: ['orderStatus', 'id', 'serviceId', 'orderDescription', 'orderScheduledDate'],
        include: [{
            model: models.User,
            attributes: ['firstName', 'phoneNumber']
        }]
    }).then(function(data) {

        res.status(200).send({
            data: data,
            serviceName: data["serviceId"]
        });

    });

});

I want: the result should return null if there is no user for the order and return order details and user when it is null.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

However, a where clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add required: false for more detail check nested-eager-loading

var users  = require('./database/models').user;

    models.Order.findOne({
    where: {
        id: req.params.id
    },attributes: ['orderStatus','id','serviceId','orderDescription','orderScheduledDate'],
    include: [
        {model: users,required: false,
        attributes: ['firstName','phoneNumber']
        }
    ]
}).then(function(data) {

    res.status(200).send({data : data,serviceName : data["serviceId"]});

});
about 4 years ago · Santiago Trujillo Relatório

0

You can add attribute required: false,

 const result = await company.findAndCountAll({
        where: conditions,
        distinct: true,
        include: [
          media,
          {
            model: tag,
            where: tagCond,
          },
          { model: users, where: userCond, attributes: ['id'] },
          {
            model: category_company,
            as: 'categoryCompany',
            where: categoryCond,
          },
          { model: media, as: 'logoInfo' },
          { model: city, as: 'city' },
          {
            model: employee,
            as: 'employees',
            required: false,
            include: [{
              model: media,
              as: 'avatarInfo',
            }],
            where: {
              publish: {
                [Op.ne]: -1,
              },
            },
          },
        ],
        order: [['createdAt', 'DESC']],
        ...paginate({ currentPage: page, pageSize: limit }),
      });
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda