My project uses express.js and sequelize.js. I am trying to filter a query based on if it has one or more associations.
Here are my models:
const Tag = sequelizeConnection.define('tag', {
title: {
type: Sequelize.STRING,
validate: {
len: [1, 255]
}
},
counter: {
type: Sequelize.INTEGER,
validate: {
min: 0
}
}
})
const Post = sequelizeConnection.define('post', {
category: {
type: Sequelize.STRING,
validate: {
notEmpty: true
}
},
title: {
type: Sequelize.STRING,
validate: {
notEmpty: true,
len: [1, 500]
}
},
description: {
type: Sequelize.TEXT,
validate: {
len: [0, 10000]
}
},
images : {
type: Sequelize.ARRAY(Sequelize.TEXT)
},
email: {
type: Sequelize.STRING,
validate: {
notEmpty: true,
isEmail: true
}
}
})
Tag.belongsToMany(Post, {through: 'postTag', foreignKey: 'tagId'});
Post.belongsToMany(Tag, {through: 'postTag', foreignKey: 'postId'});
Here is my query (it is hard coded for now for testing reasons)
router.route('/findPostsByTag')
.get((req, res) => {
PostModel.findAll({
include: [{model: TagModel, where: {title: ['cheap', 'cars']}}]
})
.then((data) => {
res.send(data)
})
.catch((err) => {
console.log(err)
res.sendStatus(500)
})
})
The query returns all posts that have the tag 'cheap', 'cars' and 'cheap' 'cars'.
I want it to return only the posts that have both the 'cheap' and 'cars' tags and exclude any post that only have one.
Any help would be appreciated! I haven't be able to find an answer in the docs or on forums for the past day!
You want to use a
$and
operator in the query docs: