Below is the code to retrieve last 10 posts from DB and return a List.
I am facing Null Pointer exception at posts.add(doc)
line.
Am I doing anything wrong?
public List<Document> findByDateDescending(int limit) {
List<Document> posts = null;
Bson sort = Sorts.descending("date");
MongoCursor<Document> cursor = postsCollection.find().sort(sort).limit(limit).iterator();
try{
while(cursor.hasNext()){
System.out.println("Whats wrong with code");
Document doc = cursor.next();
System.out.println(doc);
posts.add(doc); ----Null pointer exception
}
}
finally {
cursor.close();
}
return posts;
}