我正在使用Mongoose 5.1.7,并尝试在定义的架构中跨多个文本索引创建复合索引。这是我的架构定义:
const mongoose = require('mongoose');
const alumniSchema = mongoose.Schema({
firstName: {
type: [String],
required: true
},
lastName: {
type: [String],
required: true
},
classYear: {
type: Number,
required: true
},
photoURL: {
type: String,
},
education: [
{
school: {
type: String,
required: true
},
gradYear: {
type: Number,
required: true
},
degreeType: String,
degreeSubject: String,
}
],
jobs: [
{
employer: {
type: String,
required: true
},
position: String,
startDate: Date,
endDate: Date,
isCurrent: Boolean
}
],
contactInfo: {
phoneNumber: {
type: String,
},
email: {
type: String,
}
},
})
alumniSchema.index({ firstName: 'text', lastName : 'text', email: 'text' });
module.exports = mongoose.model('Alumni', alumniSchema);
启动服务器时,出现以下错误:
MongoError: Index: { v: 2, key: { _fts: "text", _ftsx: 1 }, name: "firstName_text_lastName_text_email_text", ns: "5b3be578c0c6e317f7c1bc2b_test.alumnis", background: true, weights: { email: 1, firstName: 1, lastName: 1 }, default_language: "english", language_override: "language", textIndexVersion: 3 } already exists with different options: { v: 2, key: { _fts: "text", _ftsx: 1 }, name: "firstName_text_lastName_text_classYear_text_education.school_text", background: true, weights: { classYear: 1, education.school: 1, firstName: 1, lastName: 1 }, default_language: "english", language_override: "language", ns: "5b3be578c0c6e317f7c1bc2b_test.alumnis", textIndexVersion: 3 }
我已经搞混了一段时间了,显然以前创建了一个索引。但是,当我使用mongo shell检查当前设置的索引时,找不到错误消息引用的索引“ firstName_text_lastName_text_classYear_text_education.school_text”:
> db
test
> db.collection.getIndexes()
[ ]
我陷入僵局-我不确定是否创建索引错误,或者是否应该删除索引(Mongoose本身不支持dropIndex()函数)。
还有其他人处理过这个问题吗?谢谢!
答案 0 :(得分:0)
看起来像Mongoose在运行时动态创建索引。我的诀窍是添加:
var Alumni = mongoose.model('Alumni', alumniSchema);
Alumni.collection.dropIndex('firstName_text_lastName_text_classYear_text_education.school_text', function(err, result) {
if (err) {
console.log('Error dropping index!', err);
}
});
,然后重新启动服务器。
当我能够将索引更改为我想要的任何值时。注意,每次我想更新索引时,我仍然需要添加以上代码段并重新启动服务器。