java.lang.ClassCastException:com.mongodb.FindIterableImpl无法强制转换为org.bson.Document

时间:2016-03-27 12:04:25

标签: java mongodb

我有以下代码

public class UserDAO {
    private final MongoCollection<Document> usersCollection;
    private Random random = new SecureRandom();

    public UserDAO(final MongoDatabase blogDatabase) {
        usersCollection = blogDatabase.getCollection("users");
    }

    public boolean addUser(String username, String password, String email) {

        String passwordHash = makePasswordHash(password, Integer.toString(random.nextInt()));    

        Document doc = new Document("_id", username).append("password", passwordHash);

        if (email != null && !email.equals("")) {

            doc = new Document("_id", username)
            .append("password", passwordHash)
            .append("email", email);
        }

        try {

            usersCollection.insertOne(doc);             
             return true;
        } catch (MongoWriteException e) {
            if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
                System.out.println("Username already in use: " + username);
                return false;
            }
            throw e;
        }
    }

    public Document validateLogin(String username, String password) {
        Document user = null;   

        user = (Document) usersCollection.find(new BasicDBObject("_id", username));// at this line I'm getting error
        if (user == null) {
            System.out.println("User not in database");
            return null;
        }

        String hashedAndSalted = user.get("password").toString();

        String salt = hashedAndSalted.split(",")[1];

        if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
            System.out.println("Submitted password is not a match");
            return null;
        }

        return user;
    }    

}

我想获得一份文件/记录,但我收到错误

java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be cast to org
.bson.Document
        at course.UserDAO.validateLogin(UserDAO.java:94)
        at course.BlogController$6.doHandle(BlogController.java:231)
        at course.BlogController$FreemarkerBasedRoute.handle(BlogController.java
:92)
        at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:139)
        at spark.webserver.JettyHandler.doHandle(JettyHandler.java:54)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandle
r.java:179)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.j
ava:136)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper
.java:97)
        at org.eclipse.jetty.server.Server.handle(Server.java:451)
        at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:252)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.jav
a:266)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConn
ection.java:240)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPoo
l.java:596)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool
.java:527)
        at java.lang.Thread.run(Thread.java:745)

我的代码中是否有任何错误,任何解决方案。

3 个答案:

答案 0 :(得分:1)

您也可以这样做:

Document user = null;
user = usersCollection.find(eq("_id", username)).first();

使用Filter.eq()来比较用户名的相等性,如果您使用了import static com.mongodb.client.model.Filters.eq;,那么只使用eq()方法。
并使用first()它返回集合中的第一个Document。

答案 1 :(得分:0)

好的,我发现这个答案在validateLogin()中做了一些更改

public Document validateLogin(String username, String password) {
        FindIterable<Document> user = null; // Change to get the object of FindIterable<Document>

        user = usersCollection.find(new Document("_id", username) );// give Document as the find() argument
        if (user == null) {
            System.out.println("User not in database");
            return null;
        }

        String hashedAndSalted = user.first().get("password").toString();// get user.first()

        String salt = hashedAndSalted.split(",")[1];

        if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
            System.out.println("Submitted password is not a match");
            return null;
        }

        return user.first();//get user.first()
    }

因此问题得到了解决。

答案 2 :(得分:0)

只需在搜索查询中添加第一个()就可以省去所有麻烦。

    Bson filter = new Document("_id",username);
    Document user = coll.find().filter(filter).first();