首页 > 解决方案 > 如何使用 mongoose 从 mongodb 模式中删除索引?

问题描述

我正在尝试使用 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);

当我使用 command 从终端在 mongo shell 中执行查询时db.usertable.find({}),我可以看到结果仍然有username字段。从架构文件中删除该字段后,我也尝试过username,但即使这样也无济于事。

提前致谢。

标签: javascriptnode.jsmongoose

解决方案


这将删除集合的所有索引,但对象 ID 除外

db.collection.dropIndexs();

删除某个索引

首先输入命令

 db.collecction.getIndexes();

在此处输入图像描述

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

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

推荐阅读