Reputation: 17999
From the mongodb doc:
Basically create an index for a sub document consists in write something like "address.city"
So far I couldn't do the same.
I tried:
index = "category.code";
index = { "category.code": 1 };
index = { "category": {code: 1} };
collection.ensureIndex( index, {unique: true, w: 1}, function(error, data){
console.log(error ? error : documentName + ': [ensureIndex] ' + JSON.stringify(data));
});
But no index created.
Is there any other solution?
When I do it from the command line via mongo
it works.
db.type.ensureIndex({'category.code':1})
But when I run it from a JS script, it doesn't.
var mongodb = require('mongodb');
exports.up = function(db, next){
var documentName = 'type';
var collection = mongodb.Collection(db, documentName);
...
I'm using https://npmjs.org/package/mongo-migrate module.
Upvotes: 0
Views: 3035
Reputation: 59773
This code works as expected in NodeJS:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test", function (err, db) {
db.collection("test").ensureIndex({ "category.code": 1 },
function(err, result) {
db.close();
});
});
Displaying the indexes for the collection:
> use test
switched to db test
> db.test.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.test",
"name" : "_id_"
}
]
> db.test.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.test",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"category.code" : 1
},
"ns" : "test.test",
"name" : "category.code_1"
}
]
Upvotes: 4