MongoError:E11000 重复键错误集合:orders.events 索引:_id_ dup 键:{_id:ObjectId('608e6a80931b45001aa7f910')}

时间:2021-05-02 09:52:45

标签: javascript node.js typescript mongodb mongoose

所以实际上我收到了这个错误。 我有 2 个模型:一个用于事件,另一个用于订单,当我找到它并按顺序引用它并尝试保存它时,我首先将事件实例从一条路由存储在数据库中,然后在其他路由上存储,然后出现以下错误

MongoError: E11000 duplicate key error collection: orders.events index: _id_ dup key: { _id: ObjectId('608e6bde6ae9e80019f01dfe') }
[orders]     at Function.create (/app/node_modules/mongodb/lib/core/error.js:57:12)
[orders]     at toError (/app/node_modules/mongodb/lib/utils.js:123:22)
[orders]     at /app/node_modules/mongodb/lib/operations/common_functions.js:258:39
[orders]     at handler (/app/node_modules/mongodb/lib/core/sdam/topology.js:944:24)
[orders]     at /app/node_modules/mongodb/lib/cmap/connection_pool.js:350:13
[orders]     at handleOperationResult (/app/node_modules/mongodb/lib/core/sdam/server.js:558:5)
[orders]     at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:277:5)
[orders]     at MessageStream.emit (node:events:369:20)
[orders]     at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
[orders]     at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:42:5)
[orders]     at writeOrBuffer (node:internal/streams/writable:395:12)
[orders]     at MessageStream.Writable.write (node:internal/streams/writable:340:10)
[orders]     at Socket.ondata (node:internal/streams/readable:750:22)
[orders]     at Socket.emit (node:events:369:20)
[orders]     at addChunk (node:internal/streams/readable:313:12)
[orders]     at readableAddChunk (node:internal/streams/readable:288:9)
[orders] [ERROR] 09:09:09 MongoError: E11000 duplicate key error collection: orders.events index: _id_ dup key: { _id: ObjectId('608e6bde6ae9e80019f01dfe') }

我的事件和订单架构如下:

事件:

const eventSchema = new mongoose.Schema({
    date: {
        type: mongoose.Schema.Types.Date,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    creatorId: {
        type: String,
        required: true
    }  
});

顺序:

const orderSchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true
    },
    event: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Event'
    }   
});

我的代码如下:

const event = await Event.findById(eventId);

if (!event) {
        throw new NotFoundError();
    }

const order = Order.build({
        userId: req.currentUser!.id,
        event
})

order.save();

我已经在数据库中存储了事件文档,我可以通过查找它来引用。

1 个答案:

答案 0 :(得分:0)

请尝试删除数据库一次并尝试添加新文档。 正如您在订单集合中提到的事件键。