MongoDB w/Mongoose-在哪里放置语法以确保跨越多个字段的索引



我正在尝试实现这个解决方案,但我不知道该把它放在哪里。我经常看到db变量被调用,但我对node和mongoDb还是新手,所以我不知道如何在我的Model中调用它。以下是确保索引跨越多个字段的语法。。。

db.collection.ensureIndex( {
    description: "text",
    title: "text"
} );

这是我的模型。。。

    //  Module dependencies.
var mongoose        = require('mongoose'),
    config          = require('../../config/config'),
    Schema          = mongoose.Schema,
    findOrCreate    = require('mongoose-findorcreate'),
    textSearch      = require('mongoose-text-search');
// Product Schema
var ProductSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    retailer: {
        type: String,
        required: true,
        trim: true
    },
    retailer_category: {
        type: String,
        required: true,
        trim: true
    },
    product_id: {
        type: String,
        required: true,
        trim: true
    },
    link: {
        type: String,
        trim: true
    },
    title: {
        type: String,
        trim: true
    },
    price: {
        type: Number
    },
    // Rating - 0 out of 5 (can be decimal)
    rating: {
        type: Number
    },
    description: {
        type: String,
        trim: true
    },
    variations: {
        type: Schema.Types.Mixed,
        default: []
    },
    images: {
        type: Boolean,
        default: false
    }
}); 
// Validations
ProductSchema.index({ retailer: 1, product_id: 1 }, { unique: true });
// Statics
ProductSchema.statics = {
    load: function(id, cb) {
        this.findOne({
            _id: id
        }).exec(cb);
    }
};
// Plug-Ins
ProductSchema.plugin(findOrCreate);
ProductSchema.plugin(textSearch);
mongoose.model('Product', ProductSchema);
var Product = mongoose.model('Product', ProductSchema);
Product.ensureIndexes( function(err) { 
    if (err) { 
      console.log(err); 
    } 
})

值得注意的是:

当您的应用程序启动时,Mongoose会自动为您的模式中的每个定义的索引调用ensureIndex。虽然这对开发来说很好,但建议在生产中禁用此行为,因为索引创建可能会对性能产生重大影响。通过将架构的autoIndex选项设置为false来禁用该行为。

来自http://mongoosejs.com/docs/guide.html

我也为这件事挠头。在挖掘了mongoose测试用例之后,我发现ensureIndex驻留在mongoose模型的集合属性中。

var ProductModel = mongoose.model('Product', ProductSchema);
ProductModel.collection.ensureIndex({
    description : 'text',
    title : 'text'
}, function(error, res) {
    if(error){
        return console.error('failed ensureIndex with error', error);
    }
    console.log('ensureIndex succeeded with response', res);
});    

请注意,回调是必需的,否则Mongo将抛出错误:

Error: Cannot use a writeConcern without a provided callback