我正在 MongoDB University 学习 MongoDB 类(class)。对于家庭作业,我已完成所需的所有操作,但在根据日期降序对博客文章进行排序时,我收到 NullPointerException。我尝试了很多事情但无法摆脱它。有谁能够帮助我?
这是我将博客文章插入数据库时的 Java 代码。
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);
这是我用来根据日期降序排序的代码。
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;
}
这是我得到的异常堆栈跟踪。
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)
最佳答案
您的问题与 MongoDB 无关。这是一个简单的 Java 错误。您可以通过以下方式声明您的列表:
List<Document> posts = null;
posts
现在是一个空指针,因此当您尝试执行 posts.add(d);
时,您会得到一个 NullPointerException
。不要初始化 posts = null
,而是将其初始化为 new ArrayList
(或另一个实现 List
的类)
List<Document> posts = new ArrayList<Document>();
关于java - MongoDB 中基于日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30869500/