Henok Tesfaye
Henok Tesfaye

Reputation: 9560

How to filter a mongo document which contain some string in one of its properties?

I have a model users that contain some basic user information. I am just adding a search functionality for my app and i want to find users which contain the search term in their displayName property?

users model

[
    {
        "_id" : ObjectId("5bbda46a433ced65ac7c4699"),
        "email" : "[email protected]",
        "displayName" : "Henok Tesfaye",
        "userId" : "5bbda46a433ced65ac7c4698",
        "reputationNumber" : 0,
        "questions" : [ 
            "5bbf135d7883513e3839a34c"
        ],
        "answers" : []
    },
    {
        "_id" : ObjectId("5bbdb84a7da23035740bf056"),
        "email" : "[email protected]",
        "displayName" : "Mezi Villager",
        "userId" : "5bbdb84a7da23035740bf055",
        "reputationNumber" : 5,
        "questions" : [ 
            "5bbf1f137883513e3839a34f"
        ],
        "answers" : [ 
            "5bbf6933e564763770d81828"
        ]
    }
]

If the search term is Henok the output must be

[
    {
        "_id" : ObjectId("5bbda46a433ced65ac7c4699"),
        "email" : "[email protected]",
        "displayName" : "Henok Tesfaye",
        "userId" : "5bbda46a433ced65ac7c4698",
        "reputationNumber" : 0,
        "questions" : [ 
            "5bbf135d7883513e3839a34c"
        ],
        "answers" : []
    }
]

.find({ displayName: "Henok" }) returns empty record.

Upvotes: 3

Views: 355

Answers (2)

IftekharDani
IftekharDani

Reputation: 3729

You can use filter in loopback in where cond.

Two way to use regex in loopback.

Model.find({
    where: {'displayName': /video/i }, //i for case-insensitive.
}, function(err, resilus) {
  console.log(resilus);
});

OR

var search = new RegExp(search, 'i'); //i for case-insensitive.

Model.find({
    where: {'displayName': search },
}, function(err, resilus) {
  console.log(resilus);
});

Upvotes: 2

Dan D.
Dan D.

Reputation: 8567

Use can use regular expression in .find(...) function:

.find({displayName: /Henok/})

Upvotes: 1

Related Questions