Mongoose SchemaType.prototype.index() 是一種用於在 Mongoose 模式中的字段上創建索引的方法。索引是一種數據結構,允許高效查詢數據庫中的數據。它可以在集合中創建一個或多個字段,以加快使用這些字段作為搜索條件的查詢。在字段上創建索引時,數據庫會創建一個單獨的數據結構,用於存儲該字段的值以及對包含每個值的文檔的引用。
用法:
SchemaType.prototype.index( options )
Parameters: 該方法僅采用一個參數:
- options (optional):指定索引選項的對象。此參數可以采用對象、布爾值、字符串或數字作為參數。
返回類型:它返回一個 SchemaType 對象作為響應。
創建節點應用程序並安裝 Mongoose:
1. 您可以使用此命令安裝此軟件包。
npm install mongoose
2.安裝mongoose模塊後,您可以在命令提示符中使用命令檢查您的mongoose版本。
npm version mongoose
3. 之後,您可以創建一個文件夾並添加一個文件,例如index.js,要運行該文件,您需要運行以下命令。
node index.js
項目結構: 項目結構將如下所示:

示例 1:在此示例中,我們為具有姓名、電子郵件、年齡和地址字段的用戶創建 Mongoose 模式。然後,我們使用 SchemaType.prototype.index() 方法在模式中的不同字段上創建各種類型的索引。定義架構並創建索引後,我們連接到 MongoDB 數據庫,創建一個新的用戶文檔,並將其保存到數據庫。最後,我們記錄新創建的用戶名。
Index.js
Javascript
const mongoose = require("mongoose");
const { Schema } = mongoose;
mongoose.set("strictQuery", true);
const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
age: Number,
address: {
street: String,
city: String,
state: String,
zip: String,
},
});
// Creating indexes on the email and age fields
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ age: 1 });
// Creating a compound index on the address fields
userSchema.index({ "address.city": 1, "address.state": 1 });
// Creating a text index on the name and address fields
userSchema.index({
name: "text",
"address.street": "text",
"address.city": "text",
"address.state": "text",
});
// Creating a 2dsphere index on the address field for
// geo-spatial queries
userSchema.index({ "address.coordinates": "2dsphere" });
// Creating a hashed index on the name field for
//efficient sharding
userSchema.index({ name: "hashed" });
// Creating a partial index on the age field for documents
// where the age field is less than or equal to 30
userSchema.index(
{ age: 1 },
{ partialFilterExpression: { age: { $lte: 30 } } }
);
const User = mongoose.model("User", userSchema);
// Connecting to a MongoDB database and creating a new user
mongoose
.connect("mongodb://localhost:27017/geeksforgeeks",
{ useNewUrlParser: true })
.then(() => {
console.log("Connected to MongoDB");
const newUser = new User({
name: "John Doe",
email: "johndoe@example.com",
age: 25,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345",
},
});
return newUser.save();
})
.then((user) => {
console.log(`Created new user: ${user.name}`);
mongoose.connection.close();
})
.catch((err) => console.error(err));
運行代碼的步驟:
1.確認是否安裝了mongoose模塊。
npm install mongoose
2. 使用以下命令運行代碼:
node index.js
輸出:

示例 2:在此示例中,我們定義了一個 movieSchema,其中包含一個名為 actor 的子文檔數組字段。然後,我們使用 index() 方法在 actors.name 字段上創建唯一索引。該索引將強製 actor 子文檔數組中 actors.name 字段的唯一性。
然後,我們使用重複的演員名稱創建一部新電影,並嘗試將其保存到數據庫中。由於actors.name字段是唯一的,MongoDB將拋出重複鍵錯誤,並且保存操作將失敗。
Index.js
Javascript
const mongoose = require("mongoose");
const { Schema } = mongoose;
mongoose.set("strictQuery", true);
const movieSchema = new Schema({
title: {
type: String,
required: true,
},
actors: [
{
name: {
type: String,
required: true,
},
character: {
type: String,
required: true,
},
},
],
});
// Creating a unique index on the 'actors.name' field within
// the 'actors' subdocument array
movieSchema.index({ "actors.name": 1 }, { unique: true });
const Movie = mongoose.model("Movie", movieSchema);
// Connecting to a MongoDB database and creating a new user
mongoose
.connect("mongodb://localhost:27017/geeksforgeeks",
{ useNewUrlParser: true })
.then(() => {
console.log("Connected to MongoDB");
const newMovie = new Movie({
title: "The Avengers",
actors: [
{ name: "Robert Downey Jr.", character: "Iron Man" },
{ name: "Chris Evans", character: "Captain America" },
{ name: "Robert Downey Jr.", character: "Tony Stark" },
// Duplicate actor name
],
});
return newMovie.save();
})
.then((movie) => {
console.log(`Created new movie: ${movie.title}`);
mongoose.connection.close();
})
.catch((err) => console.error(err));
運行代碼的步驟: 運行以下命令:
node index.js
輸出:

參考:https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-index
相關用法
- Mongoose SchemaType.prototype.immutable()用法及代碼示例
- Mongoose SchemaType.prototype.ref()用法及代碼示例
- Mongoose SchemaType.prototype.default()用法及代碼示例
- Mongoose SchemaType.prototype.unique()用法及代碼示例
- Mongoose SchemaType.prototype.validate()用法及代碼示例
- Mongoose SchemaType.prototype.get()用法及代碼示例
- Mongoose SchemaType.prototype.text()用法及代碼示例
- Mongoose SchemaType.prototype.set()用法及代碼示例
- Mongoose SchemaType.prototype.required()用法及代碼示例
- Mongoose SchemaType.prototype.select()用法及代碼示例
- Mongoose SchemaType.prototype.transform()用法及代碼示例
- Mongoose Schema Connection.prototype.asPromise()用法及代碼示例
- Mongoose Schema Connection.prototype.dropCollection()用法及代碼示例
- Mongoose Schema.prototype.virtual()用法及代碼示例
- Mongoose Schema Connection.prototype.set()用法及代碼示例
- Mongoose Schema Connection.prototype.dropDatabase()用法及代碼示例
- Mongoose Schema.prototype.plugin()用法及代碼示例
- Mongoose Schema Connection.prototype.close()用法及代碼示例
- Mongoose Schema.prototype.static()用法及代碼示例
- Mongoose Schema Connection.prototype.useDb()用法及代碼示例
- Mongoose Schema.prototype.pre()用法及代碼示例
- Mongoose countDocuments()用法及代碼示例
- Mongoose deleteMany()用法及代碼示例
- Mongoose deleteOne()用法及代碼示例
- Mongoose estimatedDocumentCount()用法及代碼示例
注:本文由純淨天空篩選整理自ianurag大神的英文原創作品 Mongoose SchemaType.prototype.index() API。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。