Search code examples
javascriptmeteormeteor-blazesimple-schema

Adding comments in meteor. Error : 'insert failed'


I've been hammering my head for the last couple of hours. I know I'm making a stupid mistake, but I cannot seem to get the code to work. I keep getting insert failed: Error: fritkotId is required error. Any help will be greatly appreciated.

I'm trying to add comment functionality into one of my objects. This is what I have now...

# collections/comments.js

// Schema Definitions
CommentSchema = new SimpleSchema({
    body: {
        type: String,
        label: 'Body'
    },
    fritkot: {
        type: String,
        label: 'fritkotId',
        autoValue: function() {
            return Session.get('fritkotId', this._id)
        },
            autoform: {
                type: 'hidden'
            }
        },
    author: {
        type: String,
        label: 'User',
        autoValue: function() {
            return this.userId
        },
        autoform: {
            type: 'hidden'
        }
    },
    createdAt: {
        type: Date,
        label: 'Created At',
        autoValue: function() {
            return new Date()
        },
        autoform: {
            type: 'hidden'
        }
    }
});


# collections/fritkots.js

import './comments.js

// Schema Definitions
FritkotSchema = new SimpleSchema({
    comments: {
        type: Array,
        optional: true
    },
    'comments.$': {
        type: Object
    },
    'comment.$.body': {
        type: String
    },
    fav: {
        type: Boolean,
        defaultValue: false,
        optional: true,
        autoform: {
            type: 'hidden'
        }
    },
    name: {
        type: String,
        label: 'Name'
    },
    address: {
        type: String,
        label: 'Address',
    },
    postCode: {
        type: String,
        label: 'PostCode'
    },
    gemeente: {
        type: String,
        label: 'Gemeente'
    },
    info: {
        type: String,
        label: 'Description'
    },
    author: {
        type: String,
        label: 'User',
        autoValue: function() {
            return this.userId
        },
        autoform: {
            type: 'hidden'
        }
    },
    createdAt: {
        type: Date,
        label: 'Created At',
        autoValue: function() {
            return new Date()
        },
        autoform: {
            type: 'hidden'
        }
    }
});

fritkotSingle.js

import './fritkotSingle.tpl.jade' //  Single Fritkot View Page


// On Creation
Template.fritkotSingle.onCreated(function() {
    let self = this;


    self.autorun(() => {

        let fritkotId = FlowRouter.getParam('fritkotId');
        self.subscribe('singleFritkot', fritkotId);
    })
});



// Helpers
Template.fritkotSingle.helpers({
    fritkot: () => {
        let fritkotId = FlowRouter.getParam('fritkotId');
        let fritkot = Fritkots.findOne( { _id: fritkotId } ) || {};

        return fritkot
    },
    editable: function () {
        return Session.equals('editFritkotId', true)
    },
    // comments: function() {
    //  // let fritkot =  Fritkots.findOne( { id: Session.get(this._id)} );
    //  let fritkot =  Fritkots.findOne( { _id: this._id } );
    //  return fritkot.comments
    // },
    commentsCount: function() {
        return Comments.find( { fritkotId: this._id} ).count();
        console.log(`There are ${Comments.find( { fritkotId: this._id} ).count()} comments written by this user`);
    }
        // comments: () => {
        // look up comments that have matching fritkotId
        // loop thru comments
    // }
});

fritkotSingle.tpl.jade

with fritkot
    if editable
        +editFritkot
    else
        .section.section--single
            article.card.card--single
                h3.card__title= name
                p.card__content{{commentsCount}} comments
                p.card__content= address
                p.card__content
                    = gemeente
                    span.card__content= postCode
                p.card__info= info
                if fav
                    button.card__btn.btn--isDenied.toggle-fav Remove from Favorites
                else
                    button.card__btn.btn--isAllow.toggle-fav Add to Favorites
                    //- button.card__btn.toggle-fav Add to Favorites
                button.card__btn.form-delete Delete
                //- button.card__btn.btn--isEdit.form-edit Edit
                button.card__btn.form-edit Edit
.section.section--comments
    +comments

newComment.js

import './newComment.tpl.jade'

Template.newComment.events({
    'click .form-save': (e) => {
        e.preventDefault();

        let body = $('.new-comment').val();


        Comments.insert({
            // check(id, String);
            body: body,
            createdAt: new Date()
        });

        console.log('A comment was inserted with this text: ' + body);
        Session.set('newComment', false);

        // FlowRouter.go('fritkotSingle');
        // console.log('redirecting');
    },
    'click .form-close': (e) => {
        e.preventDefault();

        Session.set('newComment', false);
    }
})

I'm thinking my problem is either on my Schema definitions or the way I'm calling insert on the newComment form. Somehow I need to pass the fritkotId to my a comment and insert it when I save, but I'm having problems on where to define it.


Solution

  • EDIT: So the problem was with my collection/comments.js. Apparently declaring different fields both in a SimpleSchema and when calling Comments.insert was not letting me add a Comment with the fritkotId.

    I ended up commenting out the SimpleSchema definition for the time being.

    Here is the code that actually works.

    Comments = new Mongo.Collection('comments')
    
    
    // Permissions
    Comments.allow({
        insert: (userId, doc) => {
            // return !! userId;
            return true
        },
        update: (userId, doc) => {
            return !! userId;
        },
        remove: (userId, doc) => {
            return !! userId;
        }
    });
    
    
    // Schema Definitions
    // CommentSchema = new SimpleSchema({
    //  body: {
    //      type: String,
    //      label: 'Body',
    //      min: 1,
    //      max: 140
    //  },
    //  author: {
    //      type: String,
    //      label: 'User',
    //      autoValue: function() {
    //          return this.userId
    //      },
    //      autoform: {
    //          type: 'hidden'
    //      }
    //  },
    //  createdAt: {
    //      type: Date,
    //      label: 'Created At',
    //      autoValue: function() {
    //          if (this.isInsert) {
    //              return new Date()
    //          } else if (this.isUpsert) {
    //              return { $setOnInsert: new Date }
    //          } else {
    //              this.unset()
    //          }
    //      },
    //      autoform: {
    //          type: 'hidden'
    //      }
    //  },
    //  lastUpdatedAt: {
    //      type: Date,
    //      autoValue: function() {
    //          if (this.isUpdate) {
    //              return new Date ()
    //          }
    //      },
    //      denyInsert: true,
    //      optional: true
    //  } 
    // });
    
    
    // Methods
    Meteor.methods({
        // updateComment: (id) => {
        //  Comments.update(id, {
        //      $set: { text:  }
        //  }),
        createComment: function (commentContent, fritkotId)  {
            check(commentContent, String);
            check(fritkotId, String);
    
            let currentUserId = Meteor.userId();
    
            if(currentUserId && fritkotId) {
                Comments.insert({
                    body: commentContent,
                    author: currentUserId,
                    fritkotId: fritkotId,
                    createdAt: new Date()
                });
            } else {
                throw new Meteor.Error('you must comment on a fritkot');
            }
        },
        updateComment: (id) => {
            // Session.set('editComment', true);
        },
        deleteComment: (id) => {
            Comments.remove(id);
        }
    })
    
    // Comments.attachSchema( CommentSchema );
    

    No I need to make it work with SimpleSchema