0

I want to create a function for dynamic find document in Meteor.js. For instance I have Students Collection and I want to find students by name, gender, phone.... if name is provide I want to find name like the name that is provided, if gender is provide I want to find gender which is equal to gender that is provided, if phone is provide I want to find phone like the phone that is provided, and if name or gender or phone is not provided, I want to find the all the name and all gender and all phone. In SQL Server I will create the stored Procedure like this:

Create PROCEDURE [dbo].[pG_Student]    
   @pName nvarchar(250)=null,
   @pGender nvarchar(50)=null,
   @pPhone nvarchar(100)=null
AS
BEGIN
    SELECT * FROM [dbo].[StudentView]
    WHERE (LOWER(Name) like '%'+LOWER(@pName)+'%'  or @pName is null)
    and (Gender=@pGender or @pGender is null) 
    and (LOWER([Phone]) like '%'+LOWER(@pPhone)+'%'  or @pPhone is null) 
END

With this Stored Procedure I can call with C#.

How about with Meteor.js?

Stennie
  • 63,885
  • 14
  • 149
  • 175
Phirum
  • 655
  • 2
  • 6
  • 12

1 Answers1

0

You'll just need to construct your criteria. e.g.:

var criteria = {};
if (typeof pName != 'undefined') criteria.pName = pName.toLowerCase();
if (typeof pGender != 'undefined') criteria.pGender = pGender;
if (typeof pPhone != 'undefined') criteria.pPhone = pPhone.toLowerCase();

var cursor = Students.find(criteria);

Note that in the code above I'm assuming that the data in the database is already in lower case. This allows for the most efficient search. If not, you have to use a regular expression:

MongoDB: Is it possible to make a case-insensitive query?

That, however, isn't not advisable since Mongo can't us an index. If necessary, you could create a lowercase searchable field and a mixed case display field.

Tim

Community
  • 1
  • 1
tarmes
  • 15,366
  • 10
  • 53
  • 87