繁体   English   中英

使用 mongoose 在 mongodb 模式中使用 ensureIndex

[英]using ensureIndex in mongodb schema using mongoose

我想打电话给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");
            }
        });
    });
}

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

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

根据这一定义,猫鼬会叫ensureIndex当您通过注册的型号为你mongoose.model电话。

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

mongoose.set('debug', true);

您可以使用此声明:

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

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

你可以调用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}`);
  }
});

注意:创建索引的过程是异步的。因此,当您创建唯一索引时,无法插入重复数据。 或创建索引将失败;

首先在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();

很简单,在你的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"
      }`
    )
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM