本文介绍了使用mongoose在mongodb模式中使用ensureIndex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 authorName
上调用 ensureIndex
,命令是什么以及此代码应该在哪里把它?
I would like to call ensureIndex
on the authorName
, what is the command and where in this code should I put it?
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 ,您指明该字段应该在您的架构中编入索引,如下所示:
You don't call ensureIndex
directly, you indicate that field should be indexed in your schema like this:
var schema = mongoose.Schema({
projectName : String,
authorName : { type: String, index: true }
});
根据该定义,Mongoose将调用 ensureIndex
当您通过 mongoose.model
电话注册模型时为您服务。
Based on that definition, Mongoose will call ensureIndex
for you when you register the model via the mongoose.model
call.
查看 ensureIndex
调用Mongoose正在进行的调用,通过在代码中添加以下内容来启用调试输出:
To see the ensureIndex
calls that Mongoose is making, enable debug output by adding the following to your code:
mongoose.set('debug', true);
这篇关于使用mongoose在mongodb模式中使用ensureIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!