[英]How to drop index from mongodb schema using mongoose?
I'm trying to remove an index from my mongoDB collection in node.js application using mongoose.我正在尝试使用 mongoose 从 node.js 应用程序中的 mongoDB 集合中删除索引。 I tried using
model.collection.dropIndex("username")
but it gives me an error UnhandledPromiseRejectionWarning: MongoError: index not found with name [username]
.我尝试使用
model.collection.dropIndex("username")
但它给了我一个错误UnhandledPromiseRejectionWarning: MongoError: index not found with name [username]
。
Here is my Schema这是我的架构
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);
When I perform the query in mongo shell from the terminal using command db.usertable.find({})
, I can see that the results still have username
field.当我从终端使用命令
db.usertable.find({})
在 mongo shell 中执行查询时,我可以看到结果仍然有username
名字段。 I also tried after removing the username
field from schema file, but even that didn't help.从架构文件中删除
username
段后,我也尝试过,但即使这样也无济于事。
Thanks in advance.提前致谢。
This drops all the indexes of the collection except for the object id这将删除集合的所有索引,但对象 id 除外
db.collection.dropIndexs();
to delete a certain index删除某个索引
first type the command首先输入命令
db.collecction.getIndexes();
You will see something like above the in the red square is the index name .您将看到类似上面红色方块中的内容是索引名称。
db.collection.dropIndex( { "indexname": 1 } )
Creating an index using a unique name:使用唯一名称创建索引:
db.collection('users')
.createIndex(
{ email: 1 },
{ unique: true,
name: 'users.email.unique_index' }, // here we set index name
);
and then drop the index using it's name:然后使用它的名称删除索引:
db.collection('users').dropIndex('users.email.unique_index');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.