Matt
Matt

Reputation: 1

How to insert a username into a post in meteor

I want to insert the username along with the post. When I tried adding a post using Post.insert({content: content}) the post got inserted and displayed on the client successfully. Now I try to insert a username also, so I try like this:

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

Now not only the username not inserted it fails to insert the content as well. No error. What am I doing wrong?

The above is the problem. But I did a mistake and deleted insecure package so now I can not check the results from console or inserting directly at client. So the following is the method I used. (Please be patient, I'm new to meteor, if I ask stupid questions, pardon me).

In imports/both/post.js I put:

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

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

In client/template/postsForm.js, the following code:

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

I can insert a post from server and get displayed on client but from client side I can't. And I get no error.

Upvotes: 0

Views: 64

Answers (1)

zim
zim

Reputation: 2386

are you sure it's failing on the insert? you have a "new" in front of Meteor.user(), i suspect it's failing there. try the following, which includes a null check on the user and shows any error coming from the insert:

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

you also have 'content' in quotes, which looks wrong.

Upvotes: 0

Related Questions