Im trying to produce a query from what the user has searched for. I have an array of strings which i just want to send through in the mongoDB selector, my problem is with the /text/ syntax, it works perfectly from the mongoDB console like this:
Items.find({ $or: [{name: /doc/}, {tags: /doc/}, {name: /test/}, {tags: /test/}] });
But i cannot manage to write the same syntax in javascript, i've tried several version.
var mongoDbArr = [];
searchArray.forEach(function(text) {
mongoDbArr.push({name: /text/});
mongoDbArr.push({tags: /text/});
});
return Items.find({ $or: mongoDbArr});
But it only searches for "text" and not whats in the variable. And like this:
var mongoDbArr = [];
searchArray.forEach(function(text) {
mongoDbArr.push({name: "/" + text + "/"});
mongoDbArr.push({tags: "/" + text + "/"});
});
return Items.find({ $or: mongoDbArr});
But that doesn't give me any results back. What am i missing?
me·te·or ˈmē-tē-ər. -ˌȯr. : an atmospheric phenomenon (such as lightning or a snowfall) : any of the small particles of matter in the solar system that are directly observable only by their incandescence from frictional heating on entry into the atmosphere. : the streak of light produced by the passage of a meteor.
Scientists have divided these meteorites into three main types: stony, iron, and stony-iron. Each of these types has many sub-groups. Stony MeteoritesStony meteorites are made up of minerals that contain silicates—material made of silicon and oxygen. They also contain some metal—nickel and iron.
During their journey through the atmosphere, meteors rub against air particles, creating friction and heat. The heat then vaporizes most meteors, resulting in bright streaks of light across the sky, or shooting stars.
Most meteorites reach the Earth's surface in the form of dust or very small particles after passing through the atmosphere, which is why we do not normally see them. However, believe it or not, some 17,000 meteorites fall to Earth every year.
You have to build your regular expressions with javascript:
var mongoDbArr = [];
searchArray.forEach(function(text) {
mongoDbArr.push({name: new RegExp(text)});
mongoDbArr.push({tags: new RegExp(text,"i")});
});
return Items.find({ $or: mongoDbArr});
Or use a regular expressions query with mongodb:
mongoDbArr.push({name: { $regex : text, $options:"i" } });
mongoDbArr.push({tags: { $regex : text, $options:"i" } });
To escape special characters you can do this before you use text
(from JQuery UI's source)
text = text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With