简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM