我正在使用 Node.js 和 MongoDB 以及 Mongoose。 我正在通过 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
指导我如何在 Node.js 的 MongoDB 集合上提供索引。
最佳答案
正如人们评论的那样,最好的方法是在 Mongoose 模式中设置索引。就我而言,它位于 models/Animal.js 文件中。
对于单一索引,您可以在定义架构时进行定义
var animalSchema = new Schema({
name: String,
type: String,
tags: { type: [String], index: true }
});
参见the docs了解更多信息。
对于compound indexing ,然后您可以在同一文件中的架构定义之后添加一行,如下所示:
animalSchema.index({"tags": 1, "name": 1});
Sort order是升序 (1) 或降序 (-1)。
顺便说一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1)
来获取第一个。
关于node.js - 在 MEAN 堆栈中,如何进行一次性 MongoDB 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959354/