Search code examples
mongodbmeteormeteor-autoform

Getting the _id of the record in autoform on a method-update in meteor


I am using the autoform package for meteor, but when I try to update a document in a collection, I can't seem to get the _id of the record to update it.

I am using autoform with type=method-update so I can validate it server side. When I try the code below it fails because _id is undefined.

template:

{{#autoForm collection="Lessons" doc=lesson id="updateLessonForm"  type="method-update" meteormethod="updateLesson"}}
        <fieldset>
            {{> afFieldInput name="categoryId" firstOption="(Select a Category)" options=categoryOptions}}
            {{> afQuickField name='title'}}
            {{> afQuickField name='summary' rows=2}}
            {{> afQuickField name='detail' rows=1}}
            {{> afQuickField name='extras' rows=1}}
            {{> afQuickField name='active'}}
        </fieldset>
        <button type="submit" class="btn btn-primary btn-block">Update Lesson</button>
    {{/autoForm}}

server side method:

updateLesson: function (doc) {
    check(doc, Lessons.simpleSchema());
    Lessons.update({_id: this._id}, doc);
}

UPDATE:

doc._id returns undefined

doc returns:
I20150409-23:15:22.671(-5)? { '$set': 
I20150409-23:15:22.672(-5)?    { categoryId: 1,
I20150409-23:15:22.672(-5)?      title: 'Lesson 1 update',
I20150409-23:15:22.672(-5)?      summary: 'Summary for lesson 2',
I20150409-23:15:22.672(-5)?      detail: '<p>dsffdsfd</p>',
I20150409-23:15:22.672(-5)?      extras: '<p>fdsf</p>',
I20150409-23:15:22.672(-5)?      active: false } }

Solution

  • if you print doc, you should get the document, so this._id should be changed to doc._id.

    NOTE: try using console.log to see the values you are getting,before do the update.

    console.log(this._id)//should return undefined.
    console.log(doc._id)//should return the id
    console.log(doc)//should return the doc.
    

    Update

    In order to get the _id, you should call a second parameter.

    updateLesson: function (doc,doc_id) {
        check(doc, Lessons.simpleSchema());
        Lessons.update({_id: this._id}, doc);
    }