[Fixed] Mongoose search data by object

Issue

I want to make a search in database by JSON objects.

Here is my schema:

var patientSchema = new Schema({
firstname: String,
lastname: String,
age: String,
tel: String,

work: [workSchema],

});

My angular js request, sends an JSON object which will be:

{'firstname':'value', 'lastname':'value', 'age':'age','tel':tel}

Is there a way to search for the matches directly in the Patient Schema?
so if the JSON object contains only firstname value .. it will check that

in MySQL I would do,

SELECT * FROM patients WHERE firstname LIKE '%'.json.firstname AND .....

what I’ve tested is

var filter = "{'firstname': 'value', 'lastname': 'value', 'age':'value', 'tel': 'tel'}" //sent from angularjs client

var jsonFilter = JSON.parse(filter);

Patient.find().or([
        { 'firstname': { $regex: new RegExp(filter.firstname,'i') }},
        { 'lastname': { $regex: new RegExp(filter.lastname,'i')  }},
        { 'age':{ $regex: new RegExp(filter.age,'i')  }},
        { 'tel':{$regex: new RegExp(filter.tel,'i')  }}]).exec(function(err, result) {

        if ( err)
            throw err;

        res.json(result);
    });

this works fine but ALL the data should be filled if the attributes are empty it will return undefined which will not get me the right data. since Angular JS sends only the $scope.data.

Is there a way to get all the data by my JSON object, and not rewriting all the JSON fields, because I need to make bigger filters in this project?

Solution

I do not know if it is the best way to do this, but it is a start. I would loop over your keys and build your query dynamically. By looping over your keys, you can add as many keys as you want. For each key, push your new regex to your query variable. Finally, use your result as query.

Here is the code:

var filter = {'firstname': 'value', 'lastname': 'value', 'age':'value', 'tel': 'tel'};
var query = {$or: []};
var keys = Object.keys(filter);

for(var i=0;i<keys.length;i++) {
    var item = {};
    item[keys[i]] = new RegExp(filter[key], 'i');
    query.$or.push(item);
}

Patient.find(query).exec(function(err, result) {
    if ( err)
        throw err;

    res.json(result);
});

Leave a Reply

(*) Required, Your email will not be published