Sequelize optional where clause parameters?

后端 未结 2 1658
后悔当初
后悔当初 2021-01-18 03:52

This is one thing that really annoys me! I have to write 2 different functions for almost the same query!

Say I\'ve got an API that returns posts that a

相关标签:
2条回答
  • 2021-01-18 03:56

    You could build the where object beforehand. Here's a simple example

    // Get typeIds from whatever source you have
    
    // Here's an example
    var typeIds = [1, 2, 3];
    
    // Or you could try this to build a query without typeIds
    // var typeIds = [];
    
    var whereCondition = {};
    
    if (typeIds.length > 0) {
        whereCondition['$or'] = typeIds.map(function(id) {
            return {
                typeId: id
            };
        })
    };
    
    whereCondition['cityId'] = 1;
    
    console.log(whereCondition);
    
    Post.findAll(whereCondition).then(function(posts) {
        // The rest of your logic
    });
    
    0 讨论(0)
  • 2021-01-18 04:01

    i had some similar situation , and i used template literals to define empty string as default if the field was undefined.

    User.findOne({
    where: {
      [Op.or]: [
        { email: `${req.body.email || ""}` },
        { username: `${req.body.username || ""}` },
      ],
    },
    

    })

    0 讨论(0)
提交回复
热议问题