350602 (1) [Avatar] Offline
#1
Loving the book. Found a bug I cannot solve.

Chap 5, page 116, listing 5-12.

This is the code:


Template.selectHouse.events = {
  'change #selectHouse': function (evt) {
    var selectedId = evt.currentTarget.value;
    var newId = LocalHouse.upsert(
      selectedId,
      HousesCollection.findOne(selectedId) || newHouse
    ).insertedId;
    Session.set('selectedHouseId', newId);
  }
};


It works fine on selecting a house for the first time. And then it works again selecting a second house. But selecting the first house again, the 'newId' is 'undefined. The ```upsert()``` seems not to work.

ie:
Select house 'Stephan' #=> newId === "asdf123"
Select house 'Bob' #=> newId === "xyz456"
Select house 'Stephan' #=> newId === undefined


EDIT:

Fixed it, with the line 'if (!newId) newId = selectedId;'

Template.selectHouse.events = {
  'change #selectHouse': function (evt) {
    var selectedId = evt.currentTarget.value;
    var newId = LocalHouse.upsert(
      selectedId,
      HousesCollection.findOne(selectedId) || newHouse
    ).insertedId;
    // if we are updating a house that is already in LocalHouse, we will not get back a 'insertedId'
    if (!newId) newId = selectedId;
    Session.set('selectedHouseId', newId);
  }
};


It seems that running 'upsert()' without making any actual insertion will act as an 'update()', which only returns 'numberAffected', but not 'insertedId'.

http://docs.meteor.com/#/full/upsert
stephan.hochhaus (92) [Avatar] Offline
#2
Thanks for reporting it, that one looks nasty indeed. Apparently something wrong with getting the proper value from the select object. Give me a bit to look deeper into it.

Also I'm happy you enjoy the book so far smilie

UPDATE: Just saw your update. I think this may call for a feature request(?) on Meteor to update the behavior of upsert smilie
I'll consider this...
stephan.hochhaus (92) [Avatar] Offline
#3
I checked and apparently upsert works as designed: https://github.com/meteor/meteor/issues/1715
Either way, thanks for the report and code, I have updated chapter 5 with the working code and an explanation.