【发布时间】:2018-11-11 19:10:14
【问题描述】:
我正在尝试在集合中插入新文档,但在第一个文档之后(当我尝试插入第二个文档时)mongo 显示以下错误:
MongoError: E11000 duplicate key error collection: bbdd.productions index: _id_ dup key: { : ObjectId('5b118dabefd04e51a28ffc4d') }
实际上这是有道理的,因为 "_id" : ObjectId("5b118dabefd04e51a28ffc4d") 是分配给插入的第一个文档的 id。
我读到可能有索引导致问题,但该集合只有 id 索引。
db.productions.getIndexes() 显示:
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "production_rapipizza.productions"
}
]
我尝试使用 .dropIndexes() 删除并重新启动应用程序,但没有成功(当我创建该集合的新文档时,我遇到了同样的错误)。
我认为 mongo 将相同的 ObjectId 分配给第一个文档和以下文档,但是.. 这是不可能的,是吗?
型号:
model.Production = mongoose.model("productions", new Schema({
products: {type: Array, required: true},
date: {type: Date, required: true},
user: {type: ObjectId, ref: 'users', required: true},
createdAt: {type: Date, default: Date.now}
}, {collection: 'productions', timestamps: true}));
我在节点中的查询:
app.post('/api/production', (req, res, next) => {
req.body.date = new Date(req.body.date);
const production = new model.Production(req.body);
return production.save().then(
() => res.status(200).send("La producción para el día indicado fue registrado exitosamente"))
.catch(next)
});
如果我通过 mongodb shell 执行等效操作,它可以正常工作,所以我认为我在上面的代码中做错了。这就是我所说的“等效”:
db.productions.insert({products: [ { "product" : "oneproduct", quantity : 100 } ], date : ISODate("2018-06-03T03:00:00Z"), user : ObjectId("5b0b50326b351b4527b067c6")});
我插入的第一个文档:
{ "_id" : ObjectId("5b118dabefd04e51a28ffc4d"), "products" : [ { "product" : "nameoftheproduct", "quantity" : "100" } ], "date" : ISODate("2018-06-01T03:00:00Z"), "user" : ObjectId("5b0b50326b351b4527b067c6"), "createdAt" : ISODate("2018-06-01T18:17:15.404Z"), "updatedAt" : ISODate("2018-06-01T18:17:15.404Z"), "__v" : 0 }
我们将不胜感激地收到任何帮助或想法。
【问题讨论】:
-
发布您的查询和您插入的文档
-
完成。感谢您的回复
标签: mongodb mongoose mongoose-schema