在引用另一个模式的 MongoDB 模式上创建文本索引

Create a text index on MongoDB schema which references another schema

我正在尝试使用 mongoose 向特定架构添加索引以进行文本搜索。如果我将文本索引添加到单个字段,它工作正常,也可以使用复合索引。例如这里提供的答案很好:

Full text search with weight in mongoose

但是,我正在尝试为引用其他架构的字段添加索引。例如,我的模型如下所示:

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

因此,当您执行如下所述的搜索查询时,类似以下索引的内容将不起作用:

索引:

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

搜索查询:

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

有没有人对如何为 "publisher" 和 "author" 字段添加文本索引有任何建议,我正在使用 "populate" mongodb 方法来拉在这些模式的数据中。

我认为,您正在寻找的是连接数据表并对数据总和执行查询的能力。这是你需要关系数据库的东西,MongoDB 不是。

所以我建议您改变您希望如何执行搜索的方法,例如在作者和标题中搜索您的关键字,而不是尝试同时搜索整个数据集。