簡體   English   中英

如何使用 mongoose 從 mongodb 模式中刪除索引?

[英]How to drop index from mongodb schema using mongoose?

我正在嘗試使用 mongoose 從 node.js 應用程序中的 mongoDB 集合中刪除索引。 我嘗試使用model.collection.dropIndex("username")但它給了我一個錯誤UnhandledPromiseRejectionWarning: MongoError: index not found with name [username]

這是我的架構

var mongoose = require("mongoose"),
  Schema = mongoose.Schema;

var userTable = new Schema({
  firstname: { type: String, required: true },
  lastname: { type: String, required: true },
  username: { type: String },
  salt: { type: String },
  passwordHash: { type: String },
  email: { type: String, unique: true, required: true },
  sessionToken: { type: String },
  dateCreated: { type: String, default: new Date().toString() },
  loginHistory: [String]
});

module.exports = mongoose.model("userTable", userTable);

當我從終端使用命令db.usertable.find({})在 mongo shell 中執行查詢時,我可以看到結果仍然有username名字段。 從架構文件中刪除username段后,我也嘗試過,但即使這樣也無濟於事。

提前致謝。

這將刪除集合的所有索引,但對象 id 除外

db.collection.dropIndexs();

刪除某個索引

首先輸入命令

 db.collecction.getIndexes();

在此處輸入圖片說明

您將看到類似上面紅色方塊中的內容是索引名稱。

db.collection.dropIndex( { "indexname": 1 } )

使用唯一名稱創建索引:

      db.collection('users')
      .createIndex(
        { email: 1 },
        { unique: true,
          name: 'users.email.unique_index' }, // here we set index name 
      );

然后使用它的名稱刪除索引:

 db.collection('users').dropIndex('users.email.unique_index');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM