I am trying to find an equivalent to this MongoDB query db.inventory.find( { tags: { $all: ["red", "blank"]}}) in Mongoose. I found this one in Mongoose Model.find({'field': { $in: array name }) but it gives me as results documents with all elements in the array in a document and also documents that matches at least one of the elements in the array.
Here is a code I am using to display artisans with specific specialties:
display artisans profiles route
app.post('/artisanprofile', function(req, res){
const profile = [];
const result = req.body.search;
console.log(result);
console.log(typeof result);
const specialities = result.split(" ");
console.log(specialities);
Artisan.find({
'speciality': { $in: specialities }
}, function(err, profiles) {
if(err){
console.log(err);
}
else{
console.log(profiles);
}
});
});
the documents I am looking for are ones with specialties test and test1 but I get all documents with at least one of the elements in the array specialties passed to the query.
try it
use and and for each element of specialities use $in
app.post('/artisanprofile', function(req, res){
const profile = [];
const result = req.body.search;
console.log(result);
console.log(typeof result);
const specialities = result.split(" ");
console.log(specialities);
var andObj = {}
var andArr = []
specialities.forEach(item=>{
var itemArr = []
itemArr.push(item)
andObj['$in'] :itemArr
andArr.push({speciality:andObj})
andObj = {}
})
Artisan.find({
$and : andArr
}, function(err, profiles) {
if(err){
console.log(err);
}
else{
console.log(profiles);
}
});
});