在MEAN堆栈中,如何进行一次MongoDB索引? [英] In a MEAN stack, how can I do one-time MongoDB indexing?
问题描述
我正在将Node.js和MongoDB与Mongoose一起使用. 我正以
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')
如何在node.js中配置一次以在集合上创建索引 ?
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
指导我如何在Node.js的MongoDB集合上提供索引.
Guide me on how to give index on a MongoDB collection form Node.js.
推荐答案
正如人们所评论的,最好的方法是在Mongoose模式中设置索引.就我而言,它在models/Animal.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});
排序顺序升序(1)或降序(-1).
Sort order is either ascending (1) or descending (-1).
顺便说一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1)
来获取第一个.
Btw, you can use db.animal.find().sort({tags: 1, name: 1}).limit(1)
to get the first one.
这篇关于在MEAN堆栈中,如何进行一次MongoDB索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!