相关疑难解决方法(0)

MongoDB Morphia - 独特

我正在尝试使用一致的数据库,其中用户名和电子邮件是唯一的.

http://www.mongodb.org/display/DOCS/Indexes#Indexes-unique%3Atrue

http://code.google.com/p/morphia/wiki/EntityAnnotation

我的用户类看起来像这样:

public class User {
    @Indexed(unique = true)
    @Required
    @MinLength(4)
    public String username;

    @Indexed(unique = true)
    @Required
    @Email
    public String email;

    @Required
    @MinLength(6)
    public String password;

    @Valid
    public Profile profile;

    public User() {
...
Run Code Online (Sandbox Code Playgroud)

我使用@Indexed(unique = true)注释但它不起作用.我的数据库中仍有重复项.

我有什么想法可以解决这个问题?

编辑:

我读到了关于ensureIndexes但这似乎是一个错误的方法,我不想上传重复数据,只是为了看到它真的是重复.

我想立刻阻止它.

有点像

try{

ds.save(user);
}
catch(UniqueException e){
...
}
Run Code Online (Sandbox Code Playgroud)

java mongodb morphia playframework-2.0

5
推荐指数
2
解决办法
6386
查看次数

MongoDB唯一索引不起作用

我有一部分简单的代码,由于唯一索引约束而必须失败.但是这两个对象都被添加到数据库中,并且可以查询,尽管有独特的索引.

    BasicDBObject typeUrlIndex = new BasicDBObject();
    typeUrlIndex.put(FIELD_TYPE_URL, 1);

    BasicDBObject typeUrlIndexOptions = new BasicDBObject();
    typeUrlIndexOptions.put("background", true);
    typeUrlIndexOptions.put("sparse", true);
    typeUrlIndexOptions.put("unique", true);
    typeUrlIndexOptions.put("dropDups", true);

    objects.ensureIndex(typeUrlIndex, typeUrlIndexOptions);

    // here I can check, that index is really created, and it is true.
    List<DBObject> indexes = objects.getIndexInfo();

    BasicDBObject dbo1 = new BasicDBObject(FIELD_TYPE_URL, "aaa");
    objects.save(dbo1);

    BasicDBObject dbo2 = new BasicDBObject(FIELD_TYPE_URL, "aaa");
    objects.save(dbo2);
Run Code Online (Sandbox Code Playgroud)

两个对象都被保存并获得不同的_id.

UPD. 我发现,出了什么问题.保存到数据库后,这两个对象都会获得自己的id,但实际上第二个对象没有保存(即使是给定的id也无法查询它).

感谢araqnid,给出了正确答案.不幸的是,我没有足够的评级来投票.

indexing unique-index mongodb

3
推荐指数
1
解决办法
3077
查看次数