流星插入集合似乎可以工作,但仍然是空的

Eri*_*ick 5 asynchronous meteor

我正在做一个简单的插入流星集合,看起来很有效,但是将集合留空了.

该集合在服务器上正确定义:

Meteor.publish("comments", function () {
return Comments.find();
});
Run Code Online (Sandbox Code Playgroud)

在client.js中正确订阅:

Meteor.subscribe("commments");
Run Code Online (Sandbox Code Playgroud)

并在model.js上正确设置:

Comments = new Meteor.Collection("comments");
Run Code Online (Sandbox Code Playgroud)

插入代码如下:

Meteor.methods({ 
    addComment: function (options) {
    check(options.post_id, String);
    check(options.comment, NonEmptyString);

    if (! this.userId)
        throw new Meteor.Error(403, "You must be logged in to comment.");
    if (options.comment.length > 1000) 
        throw new Meteor.Error(413, "Comment is too long");
    var post = Posts.findOne(options.post_id);
    if (! post)
        throw new Meteor.Error(404, "No such post");
 // add new comment
    var timestamp = (new Date()).getTime();
    console.log('Comment: ' + options.comment);
    console.log('Post: ' + options.post_id);
    console.log('UserId: ' + this.userId);
    var saved = Comments.insert({
        owner: this.userId,
        post_id: options.post_id,
        timestamp: timestamp,   
        text: options.comment});
    console.log('Saved: ' + saved);
   }
});
Run Code Online (Sandbox Code Playgroud)

调用插入后,控制台将打印出以下内容:

Comment:  Something 
Post: xRjqaBBEMa6qjGnDm 
UserId: SCz9e6zrpcQrKXYWX 
Saved: FCxww9GsrDsjFQAGF 
> Comments.find().count()
0
Run Code Online (Sandbox Code Playgroud)

我有几个其他集合插入工作正常(帖子是其中之一,因为你可以在代码中看到帖子ID).在文档中,ist表示如果插入错误,它将打印到控制台,但正如你所看到它似乎正在工作,但实际上是空的.

谢谢.

更新:我确实发现数据被放入数据库,但由于某种原因没有出现.我不确定为什么数据没有正确发布,因为find()上没有过滤器.

emg*_*gee 5

我不确定到底出了什么问题,但这里有一些事情需要检查.

•首先,这个:

Meteor.publish("comments", function () {
    return Comments.find();
});
Run Code Online (Sandbox Code Playgroud)

指示服务器发布Collection,但实际上并不建立集合服务器端.

您应该Comments = new Meteor.Collection("comments");在客户端和服务器上都可用.我倾向于放入一个名为model.js的文件,就像示例所做的那样.

•第二种可能性,您没有上面显示的订阅功能,例如,Meteor.subscribe("comments");如果您没有订阅功能,您的客户端将不会知道它,即使它确实存在于集合中.

您可以通过键入meteor mongoshell(运行Meteor应用程序)来测试此理论,并db.comments.find()查看您的注释是否实际位于数据库中但未订阅.

  • `Meteor.subscribe("commments");`< - 额外'm'在代码中或仅在问题中? (3认同)
  • 就是这样!谢谢!:) (2认同)