Mongoose + Expressjs - E11000重复键错误索引?

时间:2016-06-28 16:02:34

标签: node.js mongodb express mongoose

在添加第一个条目后,我不明白为什么会出现此错误:

E11000 duplicate key error index: mydb.datasets.$id_1  dup key: { : null }

我的第一个条目中没有任何空值:

{
    "index" : "9IPZMW7IL",
    "name" : "Tweets",
    "owner_name" : "xxx",
    "read_key" : "fb6f9125f4ca15c33fea89416c3351d1",
    "write_key" : "d8a6c7e5fc73b5a91aa7a533565ed1f1",
    "data" : {
        "var1" : {
            "name" : "particles"
        }
    },
    "_id" : ObjectId("57729dc20cb70952424cdbb4"),
    "created_at" : ISODate("2016-06-28T15:54:42.576Z"),
    "entries_number" : 0,
    "public" : true,
    "__v" : 0
}

以下是我的代码:

// CRUD API:
// POST/ Create new dataset request
router.post("/", helper.authenticate, function(req, res) {
    // Used to set the dataset owner
    var sessionUser = req.session.user.name;
    // Get values from the post request
    var name = req.body.name;
    var isPublic = req.body.public != undefined ? true:false;
    // Delete the values from the request body so that we only keep information about the variables
    delete req.body.name;
    delete req.body.public;

    // This is so that we can loop through the object in reverse order
    // We do that so that the fields are saved in the right order on the db
    // (this way it will appear in the right order on the 'edit' view)
    var propertiesList = [];
    for (var property in req.body) {
        if (req.body.hasOwnProperty(property)) {
            propertiesList.push(property);
        }
    }
    propertiesList.reverse();

    var variablesFields = {};
    for (var i in propertiesList) {
        console.log(propertiesList[i])
        variablesFields[propertiesList[i]] = {name:req.body[propertiesList[i]],
                                    values: Array};
    }

    // Create dataset
    Dataset.create({
        index: helper.uniqueIndex(),
        name: name,
        owner_name: sessionUser,
        read_key: hat(),
        write_key: hat(),
        public: isPublic,
        data: variablesFields
    }, function(err, dataset) {
        if (err) {
            console.log("Error creating the dataset: " + err);
            req.session.error = "A problem occured when creating the dataset. Please try again.";
        } else {
            console.log("New dataset created with id: " + dataset._id);
            req.session.success = "Dataset " + name + " created successfully.";
        }
        res.redirect("/index");
    });
});

错误:

  

创建数据集时出错:   WriteError({" code":11000," index":0," errmsg":" E11000重复键   错误索引:mydb.datasets。$ id_1 dup key:{:null   }"" OP" {"指数":" 2IPZMWHGI""名称":" PM   2"" OWNER_NAME":" XXX"" read_key":" fc31c152aa86070252c70c0304e4ca5c"" write_key&#34 ;: #&34; 238110753c8762ce4a547fa02100a299""数据" {" VAR1" {"名称":"颗粒"}},& #34; _id":" 57729dcf0cb70952424cdbb5"" created_at":" 2016-06-28T15:54:55.459Z"" entries_number&# 34;:0,"公共":真," __ v":0}})

型号:

var datasetSchema = new mongoose.Schema({
    index: {type: String, required: true, index: {unique: true}},
    name: {type: String, required: true},
    owner_name: {type: String, required: true},
    read_key: {type: String},
    write_key: {type: String},
    public: {type: Boolean, default: false},
    data: {type: Object},
    entries_number: {type: Number, default: 0},
    created_at: {type: Date, default: Date.now},
    last_entry_at: {type: Date}
});

我知道为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我通过删除最初声明为“ 的“ id ”键解决了该问题

id: { type: String, unique: true, required: true},

我删除了这一行并删除了最初的收藏集,就解决了这个问题。