3

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.

Community
  • 1
  • 1
StujayH
  • 69
  • 1
  • 9
  • 1
    Why is this so hard for people to understand? "MongoDB does **not** perform **joins**". It's the easiest term to search for on the internet. Yet people ask this every day. You should also understand that mongoose `.populate()` **is not a join**. It's just additional query(ies) made to *look like* it's a join to the basic API. –  Jun 12 '15 at 14:12
  • 4
    Well maybe you could explain to me what I am supposed to be searching for exactly. As I do not know of the correct way to achieve what I am trying to do. – StujayH Jun 12 '15 at 14:20

1 Answers1

4

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.

Naz
  • 398
  • 2
  • 6