简体   繁体   中英

sequelize dynamic construct where with Op.or javascript

const type = TYPE.get(type_name) || '[Op.or]: [{type: 1}, {type: 2}]';
await someTable.findAndCountAll({
        where: { user_id, type },
        attributes: [
          'title',
          ['description', 'desc'],
          ['createdAt', 'created'],
          ['updatedAt', 'last_modified'],
        ],
      });

So, I am trying to pass in type for the where condition. If TYPE.get(type_name) returns a value, then use the value as type, otherwise use the Op.or operation to include both type 1 and 2. However, the way I am trying to get it to work isn't working. currently, if TYPE.get(type_name) returns a value, it works. if it doesn't return a value, the where condition gets substitute into

type='[Op.or]: [{type: 1}, {type: 2}]'

which is not what I want. Does anyone know how to get this done correctly?

I was able to figure it out. Need to do the following:

  const where = type
    ? { user_id, status: 1, type}
    : { user_id, status: 1, [Op.or]: [{ type: 1 }, { type: 2 }] };

await someTable.findAndCountAll({
        where: where,
        attributes: [
          'title',
          ['description', 'desc'],
          ['createdAt', 'created'],
          ['updatedAt', 'last_modified'],
        ],
      });

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