Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor & mongoDB LIKE query

Tags:

mongodb

meteor

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?

like image 709
Snidd Avatar asked Apr 15 '13 16:04

Snidd


People also ask

What does meteor mean?

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.

What is in 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.

What happens during a meteor?

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.

Can a meteor reach Earth?

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.


1 Answers

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, "\\$&");
like image 90
Tarang Avatar answered Oct 04 '22 18:10

Tarang