I am taking course on MongoDB at MongoDB University. For the homework I have done all the things required but while sorting the blog post based on descending order of date I am getting NullPointerException. I tried many things but can't get rid of it. Can anybody help me?
Here is my Java Code when I insert the blog post in the database.
Document post = new Document();
post.append("title", title);
post.append("author", username);
post.append("body", body);
post.append("permalink", permalink);
post.append("tags", new BasicDBList());
post.put("tags", tags);
post.append("comments", new BasicDBList());
post.append("date", new BsonDateTime(System.currentTimeMillis()));
postsCollection.insertOne(post);
Here is the code that I am using to sort based on descending order of date.
public List<Document> findByDateDescending(int limit) {
// XXX HW 3.2, Work Here
// Return a list of DBObjects, each one a post from the posts collection
List<Document> posts = null;
FindIterable<Document> cursor = postsCollection.find().sort(new BasicDBObject("date", -1));
Iterator itrtr = cursor.iterator();
while(itrtr.hasNext())
{
Document d = (Document)itrtr.next();
System.out.println(d);
posts.add(d);
}
return posts;
}
and here is the exception stack trace that I am getting.
Document{{_id=55802877234b082104416d86, title=hello, author=hardik, body=hello world post, permalink=hello, tags=[hello, world, me], comments=[], date=Tue Jun 16 19:15:27 IST 2015}} Document{{_id=55802877234b082104416d86, title=hello, author=hardik, body=hello world post, permalink=hello, tags=[hello, world, me], comments=[], date=Tue Jun 16 19:15:27 IST 2015}} java.lang.NullPointerException
at course.BlogPostDAO.findByDateDescending(BlogPostDAO.java:57)
at course.BlogController$1.doHandle(BlogController.java:117)
at course.BlogController$FreemarkerBasedRoute.handle(BlogController.java:97)
at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:139)
at spark.webserver.JettyHandler.doHandle(JettyHandler.java:54)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:179)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java: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.java:266)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:240)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:596)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:527)
at java.lang.Thread.run(Thread.java:744)