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");
}
});
});
}
Following command can be used to create compound index for nested json: db. ACCOUNT_collection. createIndex({"account.id":1,"account. customerId":1},{unique:1}) Mongo json structure is like : {"_id":"648738" "account": { "id": "123", "customerId": 7879, "name": "test" .. .. } }
They store the value of a specific field or more than one fields (i.e. set of fields), which are ordered by the value of the field as indicated in the index. The ensureIndex () Method. In MongoDB, we use 'ensureIndex ()' method to create an index.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
Connecting to MongoDBMongoose requires a connection to a MongoDB database. You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With