javascript - 带 Mongoose 的 MongoDB - 在哪里放置语法以确保跨多个字段的索引?

标签 javascript node.js mongodb mongoose

我正在尝试实现 this solution而且我不确定把它放在哪里。我看到 db 变量被频繁调用,但我对 node 和 mongoDb 还是个新手,所以我不知道如何在我的模型中调用它。这是确保索引跨越多个字段的语法...

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

值得注意的是:

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false.

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

关于javascript - 带 Mongoose 的 MongoDB - 在哪里放置语法以确保跨多个字段的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23036282/

相关文章:

javascript - Ajax ResponseText 对象上的 jQuery 操作

javascript - 在一个 div 中创建相同类型的两个标签

javascript - 进行同步 JavaScript 调用的技巧

node.js - Openshift Layer4 连接,应用程序无法启动

javascript - Node 使用另一个文件中的变量

mongodb - mgo 中的 Golang 和 mongodb 查询

java - 将 JHipster/MongoDB 应用程序部署到 Heroku

javascript - Jquery/Javascript 日期选择器概念插件

node.js - MongoDB 和 Mongoose 中边界框的数据类型?

java - MongoDB 唯一索引不起作用