I want to make a params for tags and it can contain multiple tags so it must be an array.
SOLVED
I check with my console, if there are only 1 tag, tags only return tag1
. But if there are more than 1 tag, tags return ['tag1','tag2']
. example tags
PROBLEM How to .find() using $in with array
My code for now is
async function index(req, res, next) {
try {
let { limit = 10, skip = 0, q = '', category = '', tags = [] } = req.query;
let criteria = {};
...
if (tags.length) {
tags = Array.isArray(tags) ? tags : tags.split();
console.log(tags)
tags = await Tag.find({ name: { $in: tags } });
criteria = { ...criteria, tags: { $in: tags.map(tag => tag._id) } }
}
...
}
Product model schema
const productSchema = Schema({
...
// One-To-Many
tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
}, { timestamps: true });
module.exports = model('Product', productSchema);
Tag model schema
const tagSchema = Schema({
name: {
type: String,
minlength: [3, 'Min length is 3 character!'],
maxlength: [20, 'Max length is 20 character!'],
required: [true, 'Tag name must be filled!']
}
});
module.exports = model('Tag', tagSchema)
The problem is the console return empty array and I don't know what's wrong. Any idea? example empty array