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

六月ゝ 毕业季﹏ 提交于 2019-12-11 03:46:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/32959354/in-a-mean-stack-how-can-i-do-one-time-mongodb-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!