简体   繁体   English

在MEAN堆栈中,如何做一次MongoDB索引?

[英]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.

相关问题 为什么我可以在MongoDB中更新一个字段,而不更新另一个字段? (MEAN Stack) - Why can I update one field but not another in MongoDB? (MEAN Stack) 如何在节点JS MEAN堆栈中使用Mongodb查询 - How do I work with Mongodb Queries in a node JS MEAN stack 如何在均值堆栈项目中推送到文档? - how can I do a push to a document in mean stack project? 如何在 MEAN 堆栈中获取服务器时间? (MongoDB、Express、Angular、Node) - How to get the server time in the MEAN stack ? (MongoDB, Express, Angular, Node) 如何在 Mean Stack (Node.js + Mongodb) 上的用户身份验证中检查当前登录的用户? - How can I check currently logged user in user authentication on Mean Stack (Node.js + Mongodb)? 均值堆栈:如何使用nodejs expressjs和angular 6在mongodb中存储图像? - Mean Stack: How can I store image in mongodb with nodejs expressjs and angular 6? 如何在MEAN堆栈中使用orientDB - How can I use orientDB in MEAN stack 与MEAN相比,如何部署MEEN堆栈Webapp? - How do you deploy a MEEN stack webapp as opposed to a MEAN one? Node.js如何生成一次性下载链接? - How to generate a one-time download link in Node.js? 如果复选框被选中,我如何使用平均堆栈中的复选框更新我的待办事项状态,它在 mongodb 数据库中为真,否则为假 - How i can update my todo status using checkbox in mean stack if check box is checked it place true in mongodb database otherwise false
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM