[英]In a MEAN stack, how can I do one-time MongoDB indexing?
I am using Node.js and MongoDB with Mongoose. 我正在将Mongoose与Node.js和MongoDB一起使用。 I am connecting to Mongoose form Node.js as, 我正在以Node.js的形式连接到Mongoose,
db = mongoose.connect('mongodb://localhost/my_database_name')
How can configure once in node.js to create index on collection ? 如何在node.js中配置一次以创建集合索引 ?
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. 指导我如何在Node.js的MongoDB集合上提供索引。
As people have commented, the best way is to set up the index in the Mongoose schema. 正如人们评论的那样,最好的方法是在Mongoose模式中设置索引。 In my case it's in the models/Animal.js file. 就我而言,它在models / Animal.js文件中。
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: 对于复合索引 ,您可以在Schema定义之后的同一文件中添加一行,如下所示:
animalSchema.index({"tags": 1, "name": 1});
Sort order is either ascending (1) or descending (-1). 排序顺序为升序(1)或降序(-1)。
Btw, you can use db.animal.find().sort({tags: 1, name: 1}).limit(1)
to get the first one. 顺便说一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1)
来获取第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.