【问题标题】:How to drop index from mongodb schema using mongoose?如何使用 mongoose 从 mongodb 模式中删除索引?
【发布时间】:2019-09-30 08:12:51
【问题描述】:

我正在尝试使用 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 字段后,我也尝试过,但即使这样也无济于事。

提前致谢。

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    这会删除集合中除对象 id 之外的所有索引

    db.collection.dropIndexs();
    

    删除某个索引

    首先输入命令

     db.collecction.getIndexes();
    

    您会看到上面红色方块中的类似内容是索引名称。

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

    【讨论】:

    • 我不想从我的数据库中删除所有索引。我只想删除用户名。
    • 非常感谢您更新您的答案。我运行了建议的命令并得到了结果> db.usertables.dropIndex({"username": 1}); { "nIndexesWas" : 3, "ok" : 1 } 但我仍然可以看到我的数据库条目具有用户名字段。知道为什么会这样吗?
    • 如果你想删除字段,只有索引会被删除,从猫鼬模型中删除它们
    • 我运行了db.usertables.update({}, { $unset: { username: 1 } }, { multi: true });,现在用户名字段已从数据库模型中删除。谢谢。
    • 很高兴为您提供帮助
    【解决方案2】:

    使用唯一名称创建索引:

          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');
    

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2016-11-19
      • 2019-07-26
      • 2018-12-30
      • 2021-08-14
      • 1970-01-01
      • 2015-02-04
      • 2013-09-04
      相关资源
      最近更新 更多