gpt4 book ai didi

java - 当我尝试查找不存在的文档时,我的代码抛出异常

转载 作者:行者123 更新时间:2023-12-01 19:59:54 24 4
gpt4 key购买 nike

我的代码抛出此异常:线程“AWT-EventQueue-0”中的异常 java.lang.NullPointerException

当我输入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
}

}

最佳答案

我的猜测是你的 collection.find()调用返回 null,因此当您调用 MongoCursor<Document> cursor = findIterable.iterator(); 时,findIterable 实际上是 null 并且没有 iterator() 方法。

尝试检查if (findIterable)就在您的collection.find()之后代码行。

关于java - 当我尝试查找不存在的文档时,我的代码抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59010384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com