Melissa
Melissa

Reputation: 1276

In a MEAN stack, how can I do one-time MongoDB indexing?

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.

Upvotes: 2

Views: 281

Answers (1)

Melissa
Melissa

Reputation: 1276

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.

Upvotes: 5

Related Questions