Fuzzy Searching a Non-Strict Mongoose Model

1k views Asked by At

I was wandering if there is any good way to do this. I have an application that uses non-strict schemas for documents with custom fields. A user needs to be able to create a custom field, add some information to a particular document, say the field was customfield: {name: 'test', foo: 'bar'}. When performing a search like test or bar they should come up with this object. The number of documents could get quite large and numerous and have deeply nested subdocuments.

Thanks for the help! So far I've tried elmongo and mongoosatstic to no avail. Let me know if I'm going about this the wrong way, I'd love suggestions.

1

There are 1 answers

0
AudioBubble On

There really is not a nice way to do this without JavaScript processing such as what is available to $where. That is not great considering that such evaluation cannot possibly use an "index" which is the greatest optimization for "queries" to any database system.

Consider your sample:

{ 
    "customField": {
        "name": "test",
        "foo": "bar"
    }
}

If you wanted either "test" or "bar" as your search here you would need to do this:

db.collection.find(function() {
    var doc = this;
    return Object.keys(doc).some(function(key) {
        return doc[key] == "test" || doc[key] == "bar";
    });
})

A bit better way to do this is to not use "data points" as "keys" and create "flatter attributes" on entries in an array:

{
    "customFields": [
        { "name": "name", "data": "test" },
        { "name": "foo",  "data": "bar" }
    ]
}

Then you can create a simple "index" on the collection like:

db.collection.ensureIndex({ "customFields.data": 1 })

And issue a query like so:

db.collection.find({ "customFields.data": { "$in": [ "test", "bar" ] } })

And it will find the information efficiently without processing every document in the collection in order to see if the required conditions match. It can just find them in the "index" instead.