insert failed: Error: Title is required

310 views Asked by At

I'm trying to add an object to an object array that is a key in a collection entry with the following code, but I'm getting a weird response "insert failed: Error: Title is required". I'm using simple schema/autoform on meteor.

Has anyone encountered this before (and have a solution)?

Template.dashboard.events({
  'click .requestinvite'(e,t) {
    Posts.insert({ _id : $(e.currentTarget).attr('_id')},
    {$push: { invitesRequested : {username : Meteor.userId()} }}
  );
}
});

Here is the relevant Simple Schema in coffeescript

Schemas.Posts = new SimpleSchema
    title:
        type:String
        max: 60
        optional: true

    content:
        type: String
        optional: false
        autoform:
            rows: 5

    createdAt:
        type: Date
        autoValue: ->
            if this.isInsert
                new Date()

    updatedAt:
        type:Date
        optional:true
        autoValue: ->
            if this.isUpdate
                new Date()

    invitesRequested:
        type: [Object]
        optional: true
        defaultValue: []


    owner:
        type: String
        regEx: SimpleSchema.RegEx.Id
        autoValue: ->
            if this.isInsert
                Meteor.userId()
        autoform:
            options: ->
                _.map Meteor.users.find().fetch(), (user)->
                    label: user.emails[0].address
                    value: user._id
2

There are 2 answers

0
polar On

The answer was using Posts.update instead. But Ankur Soni's post lead me in the right direction to troubleshoot this down.

3
Ankur Soni On

First of all as per proper javascript assignment standards, you are doing blunder in your code.

What if your code is hacked and the click event is called without any id assigned?

Your code must be as follows.

Template.dashboard.events({
  'click .requestinvite'(e,t) {
    var id = $(e.currentTarget).attr('_id');
    if(id){
    Posts.insert(
        { 
            _id : id
        },
        {   
            $push: { 
                    invitesRequested : {username : Meteor.userId()} 
                }
        }
    );
    } else {
        //do something here when you don't have id here, or the `click` event is hacked on UI to work without id'
    }
}
});

Since your SimpleSchema is giving error regarding title field, if it is not mandatory, then kindly use optional : true at the point of defining title field.

e.g.

title: {
    type: String,
    label: "Title",
    optional: true   //<---- do this
}

NOTE: By default, all keys are required. Set optional: true to change that.