【问题标题】:How to insert a username into a post in meteor如何在流星的帖子中插入用户名
【发布时间】:2017-06-26 21:38:59
【问题描述】:

我想在帖子中插入用户名。当我尝试使用Post.insert({content: content}) 添加帖子时,帖子已成功插入并显示在客户端上。现在我也尝试插入用户名,所以我尝试这样:

var username = new Meteor.user().username;
Post.insert({content: content, username: username});

现在不仅没有插入用户名,它也无法插入内容。没有错误。我做错了什么?

以上就是问题所在。但是我犯了一个错误并删除了不安全的包,所以现在我无法从控制台检查结果或直接在客户端插入。所以下面是我使用的方法。 (请耐心等待,我是流星新手,如果我问愚蠢的问题,请原谅我)。

在 imports/both/post.js 我放了:

    export const Post = new Mongo.Collection('post');

在 server/main.js 中

    import { Post } from '/imports/both/post.js';

    Meteor.methods({
    addPost: function (content) {
    var user = Meteor.users.findOne(this.userId);
    var username = user ? user.username : 'Anonymous';
    Post.insert({content: content, username: username});
     }
    });

在client/template/postsForm.js中,如下代码:

    import { Post } from '/imports/both/post.js';

    Template.postsForm.events({
    'submit form': function(event){
    event.preventDefault();
    var content = document.getElementById('content').value;
    Meteor.call('addPost', content);
    event.target.reset();
    }
    });

我可以从服务器插入帖子并在客户端显示,但从客户端我不能。我没有错误。

【问题讨论】:

  • 你为什么在Meteor.user().username之前使用new
  • 我正在关注一个教程,它是这样显示的。
  • 你能链接到那个教程吗? zim 的答案很可能是您所需要的
  • 请检查编辑后的版本,让我知道该怎么做:)

标签: meteor meteor-blaze meteor-accounts


【解决方案1】:

您确定插入失败了吗?你在 Meteor.user() 前面有一个“新”,我怀疑它在那里失败了。尝试以下操作,其中包括对用户的空检查并显示来自插入的任何错误:

let username = Meteor.user() && Meteor.user().username;
Post.insert({content: content, username: username}, function(error) {
  if (error) {
    console.error(error);
  }
};

引号中还有“内容”,看起来不对。

【讨论】:

  • 请检查编辑后的版本,让我知道该怎么做:)
  • 在您的更新中,您说您可以从服务器插入帖子,但不能从客户端插入。我不确定你的意思是“来自客户”。你的意思是你对 Meteor 方法的调用失败了,还是你的意思是服务器的意思?我不明白。
  • 我应该从客户端(在浏览器中)输入内容,这不起作用。但是当我从服务器端输入内容时,它会显示在客户端。
  • @Matt,是的,任何成功输入的数据都应该发布到客户端并以反应方式显示。要直接在客户端输入数据,您需要 1) 安装不安全的软件包,或 2) 设置允许/拒绝规则以允许它。参考文献guide.meteor.com/security.html#allow-deny
  • 你的意思是这样的: Post.allow({ insert() { return true; } });在 server/main.js 中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多