繁体   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