0

I have the following mongo collection in my MeteorJS app:

//Server side, load all the images
Images = new Mongo.Collection('images');
Meteor.startup(() => {
  if(Images.find().count() == 0){
    for(var i = 1; i < 23; i++){
      Images.insert({
        src:"img_"+i+".jpg",
        alt:"image "+i
      });
    }
  }
});

I pass that to a template and that works. However, I then want to retrieve the MongoDB id of an image (id that is the primary key/unique ID in MongoDB). I do it with the following code:

//Client side, get the collection and load it to the template
Images =  new Mongo.Collection('images');

Template.images.helpers({images:Images.find()});

Template.images.events({
  'click .js-del-image': (event) => {
    var imageId = event._id;
    console.log(imageId);
  }
});

This gives me undefined. What am I doing wrong? I thought this._id should give me the MongoDB ID.

For the record, This is my template, the _id attribute gets filled out:

<template name="images">
        <div class="row">
      {{#each images}}
      <div class="col-xs-12 col-md-3" id="{{_id}}">
        <div class="thumbnail">
            <img class="js-image img-responsive thumbnail-img" src="{{src}}"
            alt="{{alt}}" />

            <div class="caption">
                <p>{{alt}}</p>
               <button class="js-del-image btn btn-warning">delete</button>
            </div>
         </div>
        </div> <!-- / col -->
      {{/each}}
    </div> <!-- / row -->
</template>
halpdoge
  • 642
  • 7
  • 19
  • This has nothing to do with MeteorJs. Anyway, give id to your button and then your evebt might have have an attribute event.target.id or $(event.currentTarget).prop ('id') – iiro Dec 24 '17 at 10:59
  • Hey, I think you misunderstood. I don't want the button id attribute. I want the id of the image that I'm getting from my mongoDB, since that's what I'm iterating over (I want to delete it from the DB based on the id). I'll edit the question so that it's more clear. – halpdoge Dec 24 '17 at 11:02
  • I understood. Put image id to yout button id. Id="{_id}". I think you should do the meteorjs tutorials first to understand. – iiro Dec 24 '17 at 15:07
  • @pydoge Much wow. Since you got the answer, you may want to answer your own question instead of having it in the question. – blueren Dec 25 '17 at 06:12
  • @iiro This had nothing to do with meteorjs tutorials; this had to do with the fact that I didn't know the syntax sugar of JS. – halpdoge Dec 25 '17 at 11:02
  • @blueren Good idea, will do. Thanks! – halpdoge Dec 25 '17 at 11:03

1 Answers1

0

The problem was in the declaration of a function:

  • (event) => { ... } seems to have _id of undefined.
  • function(event) {...} seems to have the correct context.

See this answer for further information about (event) => {...} vs function(){...} declarations.

halpdoge
  • 642
  • 7
  • 19