【问题标题】:In a MEAN stack, how can I do one-time MongoDB indexing?在 MEAN 堆栈中,如何进行一次性 MongoDB 索引?
【发布时间】:2016-01-02 17:51:53
【问题描述】:

我在 Mongoose 中使用 Node.js 和 MongoDB。 我以 Node.js 的形式连接到 Mongoose,

db = mongoose.connect('mongodb://localhost/my_database_name')

如何在node.js中配置一次到create index集合?

我的App的目录结构是,基于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

指导我如何在 MongoDB 集合表单 Node.js 上提供索引。

【问题讨论】:

  • 使用猫鼬你通常会想要define the indexes with the schema
  • 您好,卡尔·格罗纳,谢谢。您还可以检查我在下面的答案中写的关于将复合索引行放入 app.js 文件中的内容是否正确?

标签: node.js mongodb mongoose mean-stack


【解决方案1】:

正如人们评论的那样,最好的方法是在 Mongoose 模式中设置索引。在我的例子中,它位于 models/Animal.js 文件中。

对于单一索引,您可以在定义架构时定义

var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true }
});

请参阅the docs 了解更多信息。

对于compound indexing,您可以在同一文件中的 Schema 定义之后添加一行,如下所示:

animalSchema.index({"tags": 1, "name": 1});

Sort order 是升序 (1) 或降序 (-1)。

顺便说一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1) 获得第一个。

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2013-11-17
    • 2016-08-05
    • 2015-02-06
    • 1970-01-01
    • 2015-03-17
    • 2013-12-24
    • 1970-01-01
    相关资源
    最近更新 更多