using ensureIndex in mongodb schema using mongoose
Solution 1
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 }
});
Based on that definition, Mongoose will call ensureIndex
for you when you register the model via the mongoose.model
call.
To see the ensureIndex
calls that Mongoose is making, enable debug output by adding the following to your code:
mongoose.set('debug', true);
Solution 2
You could use this statement:
mongoose.connection.collections['my_collection'].ensureIndex({ "key": 1 }, { "unique": true }, callback);
For example you want to do some integration tests, so you will need to drop your collections rapidly.
In that case mongoose doesn't setup indexes again during runtime even if option autoIndex
is set to true
.
This answer could be useful in that case.
Solution 3
you can call Schema#index method to create index
let urlSchema = new Schema({
url: String,
status: Number
}
);
urlSchema.index({ url: 1 }, { unique: true, background: true, dropDups: true });
you can listen createing index event.
let UrlModel = mongoose.model('url', urlSchema);
UrlModel.on('index', function(error) {
if (error && error.message) {
console.log(`Url collection create index error:${error.message}`);
}
});
Note: the process of creating index is asynchronous.so when you create unique index,you cannot insert duplicate data. or creating index will fail;
Solution 4
First define index on authorName field and if you manually want invoke ensureIndex because of certain requirement then you have to set autoIndex to false. This is what your schema would look like:
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
});
And based on the requirement you can invoke ensureIndexes method on the model that you have created using this schema i.e. ProjectModel.ensureIndexes();
Comments
-
bouncingHippo almost 2 years
I would like to call
ensureIndex
on theauthorName
, 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"); } }); }); }
-
bouncingHippo over 11 yearswill having many indexes be a good thing, or will it slow down performance? i understand that a single index on a property is meant to have O (log n)
-
JohnnyHK over 11 years@bouncingHippo You only want to create the indexes that you actually need to support the query performance you require. Every index adds work when adding/edting documents and they take up disk and memory.
-
bouncingHippo over 11 yearsi edited the question a little would you mind taking a look at my attempt to find all comments by a specific user? thanks!!
-
JohnnyHK over 11 years@bouncingHippo Please post that as a separate question as it has nothing to do with indexing.
-
bouncingHippo over 11 years
-
gvaish about 11 yearsHow to define the order while defining the index? docs.mongodb.org/manual/reference/method/…
-
JohnnyHK about 11 years@MasterGaurav Order doesn't matter for single key indexes, but if you wanted to specify it you could do that via
schema.index
. -
Totty.js almost 10 yearsBut in my case doesn't call ensureIndex at all with both methods: schema.index or {... index: true, unique: true}
-
Randy L almost 9 yearsseemed to work for a 2d index on a legacy-style geo index/query. running on mongo 2.6