mongoose在数据库中find最后十个条目

我正在做一个简单的小社交networking。 我有所有的inputpost,用户等,完成。 现在唯一错误的是它几乎只是一个聊天室。 每当你在某人的网页上发布信息时,唯一可以查看的人就是当时网页上的人。 当你刷新,所有的post都没有了。 这是我发送post时的技术部分,以及我想要做的事情。

每当你发布一篇文章,它会做一些不重要的事情,我不会列出它们。 但是有一个重要的部分,把它发送给NodeJS服务器。 这是它使用的代码:

function sendPost(cont) { socket.emit("newPost", username, uid, cont, page); model.posts.unshift(new Post(username, uid, cont, page)); // You don't need to worry about this } 

正如你所看到的,它使用用户名,uid,内容和页面发出一个“newPost”。 在服务器上,它接收这个post,然后插入到数据库中。

 socket.on("newPost", function (name, id, cont, page) { var thePost = new Post({name: name, cont: cont, id: id, page: page}); console.log("Received a new post by "+thePost.name+"(ID of "+thePost.id+"), with the content of \""+thePost.cont+"\", on the page "+thePost.page); socket.broadcast.emit("Post", name, id, cont, page); console.log("Post sent!"); console.log("Putting post in database..."); thePost.save(function (err, thePost) { if (err) { console.log("Error inserting into database: "+err); } else { console.log("Put into database finished!"); } }); }); 

现在我的实际问题/问题。 无论何时加载页面,它都会向服务器发送一个请求,如下所示:

 socket.emit("getPrevious", curPage, amount); 

这工作都很好。 在服务器上,它接收并执行以下操作:

 socket.on("getPrevious", function(curPage, amount) { console.log("Someone requested a page update, sending it to them..."); Post.find({'page': curPage}).sort('-date').execFind(function(err, post){ console.log("Emitting Update..."); socket.emit("Update", post.name, post.id, post.cont); console.log("Update Emmited"); }); }); 

该代码将只能find该页面上的最新post之一。 我希望它find最后的post,然后发回他们。 即使只发生一次,当我去页面,它会显示这个:

 null says 

我的两个问题是这样的:我怎样才能find最新的post,为什么只有这个,它返回“空”?

感谢它的进步。 如果你需要任何代码,告诉我。 如果有什么不清楚的地方,告诉我。

execFindcallback中, post参数是一个post数组,而不仅仅是一个。 这就是为什么当你尝试把它当作一个单独的post的时候你null saysnull says的。

另外,如果你只想要最近的10个,你可以在你的查询链中调用limit(10) 。 你可能也应该使用exec而不是execFind因为它更清晰一些。

所以像这样:

 Post.find({'page': curPage}).sort('-date').limit(10).exec(function(err, posts){ console.log("Emitting Update..."); socket.emit("Update", posts.length); console.log("Update Emmited"); });