2

I am using Node.js and MongoDB with Mongoose. I am connecting to Mongoose form Node.js as,

db = mongoose.connect('mongodb://localhost/my_database_name')

How can configure once in node.js to create index on collection ?

The directory structure of my App is, based on this tutorial:

HTML        views/
Angular.js  public/javascript/
Express.js  routes/
Node.js     app.js
Mongoose js models/, set up in app.js
Mongo db    set up in app.js

Guide me on how to give index on a MongoDB collection form Node.js.

dethtron5000
  • 10,363
  • 1
  • 31
  • 32
Melissa
  • 1,236
  • 5
  • 12
  • 29
  • 4
    Using mongoose you will generally want to [define the indexes with the schema](http://mongoosejs.com/docs/guide.html#indexes). – Carl Groner Oct 05 '15 at 23:26
  • Hi Carl Groner, thanks. Can you also check what I wrote in the answer below about putting the compound index line in the app.js file is correct? – Melissa Oct 06 '15 at 03:24

1 Answers1

5

As people have commented, the best way is to set up the index in the Mongoose schema. In my case it's in the models/Animal.js file.

For single indexing, you can define when you define the schema

var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true }
});

See the docs for more info.

For compound indexing, you can then add a line in the same file after the Schema definition like this:

animalSchema.index({"tags": 1, "name": 1});

Sort order is either ascending (1) or descending (-1).

Btw, you can use db.animal.find().sort({tags: 1, name: 1}).limit(1) to get the first one.

Melissa
  • 1,236
  • 5
  • 12
  • 29