Use ObjectID in input form


#1

Hi,

I got a template where i fill an html table with element from my database, like this :

<table class="table table-hover table-condensed table-bordered">
   <tbody>
	{{#each proj in Project}}
	<tr><td class="{{isSelected proj._id}} eSelectProj text-center" id='{{proj._id}}'>
              {{proj.Title}}
              </td></tr>
        {{/each}}
   </tbody>
</table>

I would like to be able to select one of the row, so i tried to refer them using id field ( id=’{{proj._id}}’ ).

I catch click on a row like this :

Template.index_projet_admin.events({
	'click .eSelectProj' (event) {
		var project = {_id: event.target.id, title: event.target.outerText};
		Template.instance().dict.set('selected', project);
	}
});

And i would like to higlight selected row using an helper like this :

Template.index_projet_admin.helpers({
	isSelected(id)
	{
		var selected = Template.instance().dict.get('selected');

		return (selected !== undefined && selected._id === id) ? "active" : "";
	}
});

But that dosen’t works.
So using console.log I figured that when i call {{isSelected proj._id}}, i got id as an ObjectID() containing a field str which is the id of my element. But when i fill the id field with id=’{{proj._id}}’ i got a string like "ObjectID(“myid…”).

So how should i do to get it works ?

Thanks fo your time and your help !


#2

Your collection is created with _id as an instance of ObjectID. But your client code seems to be expecting the _id as a string. I believe that when you use the mongo console to insert() documents the default is for the _id to be generated as an ObjectID. When you insert() using JS the _id is in the string form. So you either need to repopulate your collection with _id as a string or use the toHexString() method on your proj._id before you assign it into HTML attributes and use it for comparison purposes. In any case, you cannot use the === to compare ObjectIDs you have to use EJSON.equals()


#3

Thank you for your response, that help me to make it works !

The solution was :

As it store a string in html id field, i use : id="{{proj._id._str}}" so i get only hexa value.

Then, in my event catch, i need to recreate an ObjectId with the string :

var project = {_id: new Mongo.ObjectID(event.target.id)};

And finally, as you said, i use EJSON.equals to test the 2 ObjectId :

return (selected !== undefined && EJSON.equals(selected._id, id)) ? "active" : "";

But i guess it would works if i did a test on strings of my two object :
selected._id._str === id._str

Anyway, thanks again for your time and your help !