Search code examples
mongodbmongooseloopbackjs

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" : "henoktes72@gmail.com",
        "displayName" : "Henok Tesfaye",
        "userId" : "5bbda46a433ced65ac7c4698",
        "reputationNumber" : 0,
        "questions" : [ 
            "5bbf135d7883513e3839a34c"
        ],
        "answers" : []
    },
    {
        "_id" : ObjectId("5bbdb84a7da23035740bf056"),
        "email" : "mezi@gmail.com",
        "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" : "henoktes72@gmail.com",
        "displayName" : "Henok Tesfaye",
        "userId" : "5bbda46a433ced65ac7c4698",
        "reputationNumber" : 0,
        "questions" : [ 
            "5bbf135d7883513e3839a34c"
        ],
        "answers" : []
    }
]

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


Solution

  • 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);
    });