首页 > 解决方案 > 无法将多个文档推送到集合 (11000)

问题描述

这是我的操作模型:

const mongoose = require('mongoose');

const operationSchema = mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    extract: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Extract'
    },
    normalizations: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Normalize'
    }],
    ingestions: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Ingest'
    }]
});

module.exports = mongoose.model('Operation', operationSchema);

这就是我创建操作的方式:

exports.create = async (req, res, nexr) => {
    let op = new Operation
    op.user = mongoose.Types.ObjectId(req.body.user);
    op.extract = mongoose.Types.ObjectId(req.body.extract);
    op.normalizations = [];
    op.ingestions = [];
    const operation = new Operation(op);
    try {
        await operation.save();
        console.log(operation)
        res.send(operation);
    } catch (err) {
        console.log(operation)
        res.status(500).send(err);
    }
}

任何用户、提取、规范化、摄取模型中都不存在唯一标签

当我尝试推送到 Mongo 时,第一次一切正常。

如果我尝试推送多个记录,我会从 Postman 收到此错误:

{

"driver": true,

"name": "MongoError",

"index": 0,

"code": 11000,

"keyPattern": {

    "extract.name": 1

},

"keyValue": {

    "extract.name": null

} }

标签: mongodbmongoose

解决方案


集合中只有一个文档可以缺少唯一字段。此集合中已经有一个文档缺少值或空值。您尝试插入的集合中不存在索引。所以试试这个,从数据库中删除该集合并再次运行程序。任何缺少 source_references.key 字段的文档都将被视为具有空值。如果您希望索引仅适用于具有 source_references.key 字段的文档,您可以使用 sparse:true 索引创建选项。


推荐阅读