Create a text index in MongoDB schema that references another schema

I am trying to add an index to a specific schema with mongoose to search for text. If I add a text index to the individual fields, it works fine, and also with compound indexes, that's ok. For example, the answer provided here is great:

Full text search with mongoose weight

However, I am trying to add an index to fields that are links to other schemas. For example, my model looks like this:

    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 doing 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 for adding a text index to the publisher and author fields, I am using mongodb's fill method to pull the data for these schemas.

+3


source to share


1 answer


I think you are looking for a way to join tables of data and query on the sum of that data. For this you need a relational database, which MongoDB does not exist for.



Therefore, I recommend that you change your approach in how you would like to preform your search, for example. find the keyword in both the author and the title, instead of searching the entire dataset at the same time.

+3


source







All Articles