2016-12-26 28 views
0

對於Java來說是新手,對不起,如果這個明顯的錯誤。此外,我試圖搜索與我的問題有關的所有問題,但他們都沒有解決。mongoDB + Java-8:java.lang.NullPointerException:對於用戶沒有任何價值

我試圖獲取mongoDB集合中的所有文檔,並將它們放入數組中。 上午正確讀取的文件,我可以全部打印出來在控制檯:

public List<Item> findAll() { 
     List<Item> items = new ArrayList<>(); 
     try { 
      collection.find().forEach(document -> { 
       System.out.println(document); 
      }); 
      return items; 
     } catch (Exception e) { 
      System.out.println("Error fetcing all items " + e); 
      return items; // should be logging 
     } 
    } 
然而

當我添加這兩條線:

System.out.println(document); 
Item item = new Item((BasicDBObject) document); //line causing the error 
items.add(item);//line causing the error 

我得到這個錯誤:

java.lang.NullPointerException: no value for: users 

的商品分類代碼:

package io.app.item.model; 

import com.mongodb.BasicDBObject; 
import org.bson.types.ObjectId; 

import java.util.Date; 

public class Item { 

    private final String id; 
    private final String name; 
    private final int users; 
    private Date updated_at = new Date(); 
    private Date created_at = new Date(); 

    public Item(BasicDBObject dbObject) { 
     this.id = ((ObjectId) dbObject.get("_id")).toString(); 
     this.name = dbObject.getString("name"); 
     this.users = dbObject.getInt("users"); 
     this.updated_at = dbObject.getDate("updated_at"); 
     this.created_at = dbObject.getDate("created_at"); 
    } 

    public String getId() { 
     return id; 
    } 

    public int getUsers() { 
     return users; 
    } 

    public String getName() { 
     return name; 
    } 
} 

我註釋掉從Item類提起users然後一切工作沒有真正的工作我還是不知道爲什麼加入integer類型的字段也導致了問題的時候刪除它換來的是在這種形狀:

[[email protected], [email protected]] 

請注意使用mongoldb 3.4.1驅動程序。 文件示例:

{ 
    "_id": { 
     "$oid": "586140b25fa86a1e760d92fe" 
    }, 
    "name": "item1", 
    "created_at": { 
     "$date": "2016-12-26T16:09:22.949Z" 
    } 
} 
+2

請[編輯]你的問題包括與空指針異常進入整個堆棧跟蹤。你還應該包含這個'Item'類的源代碼。 – Kenster

+0

添加了仍然試圖弄清楚如何包含堆棧跟蹤的項目類代碼。 – user3462064

回答

0

這是您如何閱讀和從Mongo Collection中映射。這是針對MongoDB 3.x驅動程序的。

更改您的構造函數以獲取Document。

public List<Item> findAll() { 
    List<Item> items = new ArrayList<>(); 
    FindIterable<Document> find = collection.find(); 
    if (find == null) { 
     return null; 
    } 
    for (Document current : find) { 
     Item item = new Item(current); 
     items.add(item); 
    } 
    return items; 
} 

添加拉姆達

List<Item> items = collection.find().map(Item::new).into(new ArrayList<>()); 
+0

正如我在問題描述中所解釋的,我沒有發現使用java-8樣式獲取文檔的問題,但是問題是試圖將集合文檔添加到數組列表中。 – user3462064

+0

是的問題是你正在做的每一個文檔類型是一個可變的操作。你需要一個Java 8解決方案嗎?簡單的循環會做。 – Veeram

+0

添加了一個lambda將文檔映射到項目。 – Veeram