11

我想调用ensureIndexauthorName命令是什么,我应该把它放在这段代码的什么地方?

var mongoose = require('mongoose');

// defines the database schema for this object
var schema = mongoose.Schema({
    projectName : String,
    authorName : String,
    comment : [{
        id : String,                                    
        authorName : String,
        authorEmailAddress : { type : String, index : true }    
    }]
});

// Sets the schema for model
var ProjectModel = mongoose.model('Project', schema);

// Create a project
exports.create = function (projectJSON) {
    var project = new ProjectModel({
        projectName : projectJSON.projectName,
        authorName : projectJSON.authorName,    

        comment : [{
            id : projectJSON.comments.id,                                           
            authorName : projectJSON.comments.authorName,                           
            authorEmailAddress : projectJSON.authorEmailAddress
        });

        project.save(function(err) {
            if (err) {
                console.log(err);
            } else{
                console.log("success");
            }
        });
    });
}
4

5 回答 5

31

您不ensureIndex直接调用,您指示该字段应在您的架构中建立索引,如下所示:

var schema = mongoose.Schema({
  projectName : String,
  authorName : { type: String, index: true }
});

根据该定义,ensureIndex当您通过调用注册模型时,Mongoose 会为您mongoose.model调用。

要查看ensureIndexMongoose 正在进行的调用,请通过将以下内容添加到您的代码中来启用调试输出:

mongoose.set('debug', true);
于 2012-11-07T15:38:39.407 回答
14

您可以使用以下语句:

mongoose.connection.collections['my_collection'].ensureIndex({ "key": 1 }, { "unique": true }, callback);

例如,您想做一些集成测试,因此您需要快速删除您的集合。在这种情况下,即使选项autoIndex设置为,猫鼬也不会在运行时再次设置索引true。在这种情况下,这个答案可能很有用。

于 2014-11-14T13:14:58.127 回答
4

您可以调用 Schema#index 方法来创建索引

let urlSchema = new Schema({
    url: String,
    status: Number
  }
);
urlSchema.index({ url: 1 }, { unique: true, background: true, dropDups: true });

您可以收听创建索引事件。

let UrlModel = mongoose.model('url', urlSchema);
UrlModel.on('index', function(error) {
  if (error && error.message) {
    console.log(`Url collection create index error:${error.message}`);
  }
});

注意:创建索引的过程是异步的,所以创建唯一索引时,不能插入重复数据。否则创建索引将失败;

于 2017-05-13T03:12:37.390 回答
1

首先在 authorName 字段上定义索引,如果由于某些要求而手动调用 ensureIndex 则必须将autoIndex 设置为 false。这就是您的架构的样子:

var schema = mongoose.Schema({
    projectName : String,
    authorName : {type : String, index : true}
    comment : [{
        id : String,                                    
        authorName : String,
        authorEmailAddress : { type : String, index : true }    
    }]
}, {
     // Turn-off auto indexing, we manually need to trigger indexing 
     autoIndex : false 
});

根据要求,您可以在使用此模式创建的模型上调用 ensureIndexes 方法,即 ProjectModel.ensureIndexes();

于 2016-03-24T19:52:13.720 回答
0

很简单,在你的 MongoDB 连接中添加

mongoose.connect(
  process.env.ENVIRON === "production"
    ? process.env.MONGODB_REMOTE
    : process.env.MONGODB_LOCAL,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    autoCreate: true,
    autoIndex: true, // This enables indexing for you
    
  },
  () =>
    console.log(
      `Connected to ${
        process.env.ENVIRON === "production"
          ? "Production DB"
          : "Development DB"
      }`
    )
);
于 2021-08-13T15:25:32.840 回答