[英]Mongoose doesn't create index
我在 node/express/mongoose 項目中有兩個模式 - 用戶和對話。 我已經在每個模式上添加了索引。 在檢查我的(免費)Mongo Atlas Cluster 中的索引時,我可以看到 Conversation 的索引已創建。 但是,用戶不會創建所需的索引。
這是我的用戶架構:
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const userSchema = new Schema( { username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, age: { type: String}, location: { type: { type: String, enum: ["Point"], default: "Point" }, coordinates: { type: [Number], default: [0, 0] }, }, }, { timestamps: true } ); userSchema.index({ age: 1, location: "2dsphere", username: 1 }); module.exports = mongoose.model("User", userSchema);
在 Mongo Atlas 中,用戶集合上有兩個索引: id
(當然)和email
。 我從未要求索引 email。 age
、 location
和username
未編入索引。 如何解決這個問題?
由於 mongoose 文檔( https://mongoosejs.com/docs/guide.html#indexes ),您可以在路徑級別的架構中進行字段級別索引。 例如,如果您需要索引年齡,您可以在架構中執行以下操作:
age: { type: String, index: true},
您正在嘗試在代碼中創建一個由 2dsphere 索引組成的復合索引。 我想這不是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.