在 MEAN 堆栈中,如何进行一次性 MongoDB 索引?
In a MEAN stack, how can I do one-time MongoDB indexing?
我在 Mongoose 中使用 Node.js 和 MongoDB。
我正在连接到 Mongoose 表单 Node.js 作为
db = mongoose.connect('mongodb://localhost/my_database_name')
如何在 node.js 中配置一次到 create index 收集?
我的应用程序的目录结构是,基于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 上提供索引。
正如人们评论的那样,最好的方法是在 Mongoose 架构中设置索引。在我的例子中,它在 models/Animal.js 文件中。
对于单索引,可以在定义schema的时候定义
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)
获得第一个。
我在 Mongoose 中使用 Node.js 和 MongoDB。 我正在连接到 Mongoose 表单 Node.js 作为
db = mongoose.connect('mongodb://localhost/my_database_name')
如何在 node.js 中配置一次到 create index 收集?
我的应用程序的目录结构是,基于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 上提供索引。
正如人们评论的那样,最好的方法是在 Mongoose 架构中设置索引。在我的例子中,它在 models/Animal.js 文件中。
对于单索引,可以在定义schema的时候定义
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)
获得第一个。