【问题标题】:Is the 'name' field in mongoDB automatically an index?mongoDB 中的“名称”字段是否自动成为索引?
【发布时间】:2017-07-07 22:48:00
【问题描述】:

这是我得到的错误: MongoError insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.events.$name_1 dup key: { : "Event name" }

Mongo 说字段 '_id' 和 'name' 是索引。这是名称字段的条目。

我删除了索引,如下所示:Mongoose - caused by :: 11000 E11000 duplicate key error index?,它现在可以完美运行。但为什么要从索引开始呢? 是否有自动设置为索引的字段?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var eventSchema = new Schema({
    name: {
        type: String,
        required: true
    }
    //other fields
});

eventSchema.index({ name: 0 });
mongoose.model('Event', eventSchema);

PS:我尝试使用eventSchema.index({ name: 0 }); 删除索引,但它似乎没有做任何事情。

【问题讨论】:

  • 您是否尝试过手动删除索引db.events.dropIndex({ "name": 1 })

标签: node.js mongodb mongoose


【解决方案1】:

默认情况下,MongoDB 仅将 _id 设置为索引。

当您创建集合时,您为字段 name 添加索引,就像这样 eventSchema.index({ name: 0 });

现在coolection Event 具有字段名称的索引。

为了修复它,你可以做一些事情。

1) 使用 @chridam 建议之类的代码删除索引。不要忘记从代码中删除eventSchema.index({ name: 0 });。因为它将在下次运行时再次创建索引。

2) 从数据库中删除集合。删除此行eventSchema.index({ name: 0 });。再次运行代码。现在集合将没有索引。

3) 或者您可以使name 索引不唯一。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 2012-08-14
    • 2017-03-20
    • 1970-01-01
    • 2019-02-23
    • 2011-04-12
    • 2016-01-27
    • 2021-08-16
    相关资源
    最近更新 更多