Mel*_*ssa 2 mongoose mongodb node.js mean-stack
我在 Mongoose 中使用 Node.js 和 MongoDB。我正在通过 Node.js 连接到 Mongoose,
db = mongoose.connect('mongodb://localhost/my_database_name')
Run Code Online (Sandbox Code Playgroud)
如何在 node.js 中配置一次以在集合上创建索引?
我的应用程序的目录结构基于本教程:
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
Run Code Online (Sandbox Code Playgroud)
指导我如何在 Node.js 的 MongoDB 集合上提供索引。
正如人们所评论的那样,最好的方法是在 Mongoose 模式中设置索引。在我的例子中,它在 models/Animal.js 文件中。
对于单一索引,您可以在定义架构时进行定义
var animalSchema = new Schema({
name: String,
type: String,
tags: { type: [String], index: true }
});
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档。
对于复合索引,您可以在同一文件中的 Schema 定义之后添加一行,如下所示:
animalSchema.index({"tags": 1, "name": 1});
Run Code Online (Sandbox Code Playgroud)
排序顺序是升序 (1) 或降序 (-1)。
顺便说一句,您可以使用db.animal.find().sort({tags: 1, name: 1}).limit(1)
来获得第一个。