Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a text index on MongoDB schema which references another schema

I am trying to add an index to a certain Schema with mongoose for text searches. If I add a text index to individual fields it works fine, also with compound indexes it is okay. For example the answer provided here is great:

Full text search with weight in mongoose

However, I am trying to add an index to fields which are references to other Schemas. For example my model looks like the following:

    var Book = new Schema({
        "title": String,
        "createdAt": Date,
        "publisher": {
             "type": Schema.ObjectId,
             "ref": "Publisher"
        },
        "author": {
             "type": Schema.ObjectId,
             "ref": "Author"
        },
        "isbn": String
    });

So something like the following indexing doesn't work when you perform a search query as described below:

Indexing:

 Book.index({"title": "text", "publisher.name": "text", "author.firstName": "text"});

Search query:

function searchBooks(req, res) {
    var query = req.query.searchQuery;

    Book.find({ $text: { $search: query } })
        .populate('author publisher')
        .limit(25)
        .exec(function(err, books) {
            if (err) {
                res.json(err);
            } else {
                res.json(books);
            }
        }
    );
}

Does anyone have any suggestions of how to add a text index in for the "publisher" and "author" fields, I am using the "populate" mongodb method to pull in the data for these schemas.

like image 336
StujayH Avatar asked Nov 28 '25 06:11

StujayH


1 Answers

I think, what you are looking for is the ability to join tables of data and perform a query against the sum of that data. That is something you need a relational database for, which MongoDB isn't.

So I recommend you change your approach in how you would like to preform your search, e.g. search for your keyword within both author and title instead of attempting to search the whole dataset at the same time.

like image 114
Naz Avatar answered Nov 29 '25 19:11

Naz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!