Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

javascript - 错误处理:E11000重复键错误收集(Error Handling: E11000 duplicate key error collection)

I am having a problem with the user model that I'm using with Mongoose and MongoDB to create each profile in my database.(我在Mongoose和MongoDB上使用的用户模型在数据库中创建每个配置文件时遇到问题。)

It works fine to post one user, but throws the following error if I logout and try again:(发布一个用户可以正常工作,但是如果我注销并重试,则会引发以下错误:)
{
    "name": "MongoError",
    "message": "E11000 duplicate key error collection: CourtAPIDev.users index: trackers.case_id_1 dup key: { : null }",
    "driver": true,
    "index": 0,
    "code": 11000,
    "errmsg": "E11000 duplicate key error collection: CourtAPIDev.users index: trackers.case_id_1 dup key: { : null }"
}

According to mongoose documentation: If there is more than one document (a second user) without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.(根据猫鼬的文档: 如果有多个文档(第二个用户)没有索引字段的值,或者缺少索引字段,则索引构建将失败,并出现重复的键错误。)

I don't know how to set this _id property for the trackers property –– I thought it generated automatically!(我不知道如何为trackers属性设置此_id属性–我以为它是自动生成的!)

Here's the trackers part of my Schema.(这是我的架构的跟踪器部分。)

And the relevant case_id property, which seems to be throwing the "null" error.(以及相关的case_id属性,该属性似乎抛出了“ null”错误。)

在此处输入图片说明 在此处输入图片说明

The whole repository can be found on my Github here, but the likely problem spots are the ones I highlighted, I think.(整个存储库都可以在我的Github上找到,但是我认为可能是我强调的问题点。)

Here's the github link: https://github.com/KingOfCramers/node_login_with_trackers(这是github链接: https : //github.com/KingOfCramers/node_login_with_trackers)

user model:(用户模型:)

const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        trim: true,
        minLength: 1,
        unique: true,
        validate: {
            validator: (value) => {
                return validator.isEmail(value);
            },
            message: '{VALUE} is not a valid email'
        }
    },
    password: {
        type: String,
        required: true,
        minlength: 6
    },
    tokens: [{
        access: {
            type: String,
            required: true
        },
        token: {
            type: String,
            required: true
        }
    }],
    trackers: {
        tweets: [TwitterSchema],
        legislation: [LegislationSchema],
        court_cases: [CourtCaseSchema]
    },
    frequency: [EmailSchema]
});

Express route:(快速路线:)

app.post("/users", (req,res) => {
    var body = _.pick(req.body, ['email', 'password']);
    body.frequency = {
        alert_time: new Date(),
        email: req.body.email
    }
    var user = new User(body);

    user.save().then(() => {
        return user.generateAuthToken();
    }).then((token) => {
        res.header("x-auth", token);
        res.send(user);
    }).catch((e) => {
        res.status(400).send(e);
    });
});

Test (mocha):(测试(摩卡):)

 it("Should post a new user", (done) => {
        var email = "[email protected]"
        var password = "9webipasd"
        supertest(app)
            .post("/users") // Post request to the /todos URL
            .send({
                email,
                password
            })
            .expect(200)
            .expect((res) => {
                expect(res.headers).toIncludeKey('x-auth')
                expect(res.body._id).toExist();
                expect(res.body.email).toBe(email);
            })
            .end((err) => {
                if(err){
                    return done(err);
                }
                User.findOne({email}).then((user) => {
                    expect(user).toExist();
                    expect(user.password).toNotBe(password);
                    done();
                }).catch((e) => done(e));
            });
    });
  ask by Harry Cramer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My guess is that there is an index on CourtCaseSchema.case_id which does not allow duplicates.(我的猜测是在CourtCaseSchema.case_id上??有一个不允许重复的索引。)

I think you could check (in a mongo shell) that with CourtAPIDev.court_cases.getIndexes() (I think your db is named CourtAPIDev and the collection is named court_cases but I am not sure about that).(我认为您可以使用CourtAPIDev.court_cases.getIndexes()检查(在mongo shell中)(我认为您的数据库名为CourtAPIDev ,而集合名为court_cases但我不确定)。)

Also if you clean the test db after each run, that would explain why the tests are passing, since there is no more than one user.(同样,如果您在每次运行后清理测试数据库,那也可以解释为什么测试通过了,因为最多只能有一个用户。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...