8

我正在制作一个简单的小型社交网络。我已经完成了所有的输入帖子、用户等。现在唯一的问题是它几乎只是一个聊天室。每当您在某人的页面上发布内容时,唯一可以查看它的人就是当时页面上的人。当您刷新时,所有帖子都消失了。这是发送帖子时我正在做什么以及我想要做什么的技术部分。

每当您发布帖子时,它都会做一些不重要的事情,我不会列出它们。但是有一个部分很重要,将其发送到 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”。在服务器上,它接收带有这个的帖子,然后插入到数据库中。

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");
    });
});

该代码只会找到该页面上的最新帖子之一。我希望它找到最后的帖子,然后将它们发回。即使它只发生一次,当我转到页面时,它也会显示:

null says

我的两个问题是:我如何让它找到最新的帖子,为什么只有这个,它会返回“null”?

提前谢谢它。如果您需要任何代码,请告诉我。如果有什么不清楚的,请告诉我。

4

1 回答 1

16

execFind回调中,post参数是一个帖子数组,而不仅仅是一个。这就是为什么null 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");
});
于 2013-05-24T02:23:07.607 回答