java 当我尝试查找不存在的文档时,代码引发异常

hs1ihplo  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(98)

我的代码抛出这个异常:线程“AWT-EventQueue-0”中出现异常。
当我输入mongodb在数据库中找不到的用户名或密码时,它会抛出异常。我尝试了很多方法来调试它,但我找不到抛出异常的语句。
问题是,当用户名或密码在数据库中不匹配时,我希望向用户显示一条消息

public class GetEmployee {

MongoClient mongoClient = MongoClients.create();
MongoDatabase db = mongoClient.getDatabase("MirandasShoes");
MongoCollection<Document> collection = db.getCollection("Employees");

public Employee getEmployee(String username, String password) {
    FindIterable<Document> findIterable = collection.find(new Document("Username", username).append("Password", password));
    MongoCursor<Document> cursor = findIterable.iterator();
    Employee e = new Employee();
    if (cursor.hasNext()) {
        Document doc = cursor.next();
        //ArrayList<Object> o = new ArrayList<>(doc.values());
        e.setId(doc.get("_id").toString());
        e.setName(doc.get("Name").toString());
        e.setAddress(doc.get("Address").toString());
        e.setEmail(doc.get("Email").toString());
        e.setPhone(doc.get("Phone").toString());
        e.setUsername(doc.get("Username").toString());
        e.setPassword(doc.get("Password").toString());
    }
    return e;//Get the shoes
}

}

mnemlml8

mnemlml81#

我猜collection.find()调用返回null,所以当调用MongoCursor<Document> cursor = findIterable.iterator();时,findIterable实际上是null,并且没有iterator()方法。
尝试在collection.find()代码行之后检查if (findIterable)

l2osamch

l2osamch2#

This works!!!
if (dealsInMongo.iterator() != null) {
}

相关问题