Alexey
Alexey

Reputation: 449

How to do "WHERE" in Sequelize, but EXCLUDE nested Model?

There are two models: User and Client.

Client.hasMany(User);
User.belongsTo(Client);

Next, I'm doing:

User.findAll({
    include: [{
        model: Client,
        where: {
            id: “1”
        }
    }]
});

This code works fine, but includes Client model in final output with all attributes. How can I still do “where” statement, but exlcude Client model at all?

Upvotes: 5

Views: 6229

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58613

You can do that 2 ways

User.findAll({
    attributes : ['User.*'] // might be user.* or users.* . as per your query genetaion
    include: [{
        model: Client,
        where: {
            id: "1"
        }
    }]
});

//OR

{
  attributes: {
    include: [], // define columns that you want to show
    exclude: [] // define columns that you don't want 
  }
}

Upvotes: 3

rayepps
rayepps

Reputation: 2092

Its a little janky and not really what you want but I had a similar situation and I solved it like this.

new Promise((resolve, reject) => {
  User.findAll({
    include: [{
      model: Client,
      where: {
        id: "1"
      }
    }]
  }).then(users => {
    users.forEach(u => u.client = null);
    resolve(users);
  }).catch(e => {
    reject(e);
  });
});

So your wrapping the request in a promise and grading the result of the querying, removing the property you don't want (I just nulled it out but you could get more creative mapping the object if wanted), then return the object as you like.

TLDR;
You can't (afaik). You have to do something like this if your absolutely do not want the client in the response.

Upvotes: 0

Related Questions