带有Mongoose的Node JS中的全文search
我试图对Mongoose中的string数组执行全文search,我得到这个错误:
{ [MongoError: text index required for $text query] name: 'MongoError', message: 'text index required for $text query', waitedMS: 0, ok: 0, errmsg: 'text index required for $text query', code: 27 }
但是,我确实在用户架构上的字段上声明了一个文本索引,我确认文本索引已经创build,因为我正在使用mLab。 我正在尝试在字段上执行全文search
这是我的用户架构:
var userSchema = mongoose.Schema({ local: { firstName: String, lastName: String, username: String, password: String, fields: {type: [String], index: true} } });
这里是我的全文search代码:
User.find({$text: {$search: search}}, function (err, results) { if (err) { console.log(err); } else { console.log(results); } });
要使$text
查询起作用,mongodb需要使用文本索引来索引字段。 通过mongoose使用来创build这个索引
fields: {type: [String], text: true}
在这里查看文本索引的mongodb文档。
您需要像下面一样向您的模式添加文本索引:
userSchema.index({fields: 'text'});
或者使用userSchema.index({'$**': 'text'});
如果你想包括所有的string字段