使用mongoose在mongodb模式中使用ensureIndex

bou*_*ppo 8 javascript indexing mongoose mongodb

我想打电话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");
            }
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 26

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

var schema = mongoose.Schema({
  projectName : String,
  authorName : { type: String, index: true }
});
Run Code Online (Sandbox Code Playgroud)

根据该定义,ensureIndex当您通过mongoose.model呼叫注册模型时,Mongoose会呼叫您.

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

mongoose.set('debug', true);
Run Code Online (Sandbox Code Playgroud)


Fel*_*ikZ 12

您可以使用此声明:

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

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