gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:14:22 26 4
gpt4 key购买 nike

我正在尝试实现 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com