如何使用猫鼬从mongodb模式中删除索引?

时间:2019-05-13 11:10:00

标签: javascript node.js 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字段后,我也尝试过,但是即使这样也没有帮助。

谢谢。

1 个答案:

答案 0 :(得分:1)

这会删除集合的所有索引(对象ID除外)

db.collection.dropIndexs();

删除特定索引

首先键入命令

 db.collecction.getIndexes();

enter image description here

您将看到在红色正方形上方的类似内容是索引名称。

db.collection.dropIndex( { "indexname": 1 } )
相关问题