How to prevent adding duplicated entry to database

I have a helper for a template called arrows. I pasted here only the relevat part of the code. This code check if the user exist in SeenEvents collection and should prevent adding entries with same userid to the collection. The problem is that it is not working every time I refresh the page a new entry is added to SeenEvents with same userid.

Template.arrows.helpers({

getImages: function (userId) {
           var seeneventsobject
        seeneventsobject = SeenEvents.findOne({userid:Meteor.userId()})
        if (!seeneventsobject){
            seeneventsobjects = {userid : Meteor.userId(), seenevents:{}}
            if(seeneventsobjects){
                SeenEvents.upsert({_id:seeneventsobjects._id}, seeneventsobjects);
            }
            else{SeenEvents.insert( seeneventsobjects)}
        }<img src="/uploads/default/original/2X/3/3609366d31f7447d31eb4e5ecb82eaf8189c45f2.jpg" width="302" height="175"><img src="/uploads/default/original/2X/7/76e69f6fb3e3be500d77a1091bd29127f2839c96.jpg" width="279" height="126">

I am confused by your code.

  • Relying on a check for existence before inserting is risky - you are opening the code to a race condition.
  • You are using seeneventsobject and seeneventsobjects - is this deliberate?
  • Your logic is the wrong way round (you insert if found).
  • You have a redundant test where you set an object and then check to see if it’s set (hint: it is).
  • upsert updates or inserts, so you don’t need both.
  • You don’t seem to change the seenevents property of the seeneventsobject(s)
  • Your helper doesn’t return anything to your template.

Having said all that, I’ve rewritten your code to address some of the above:

Template.arrows.helpers({
  getImages() {
    const seenEventsObject = SeenEvents.findOne({ userid: Meteor.userId() });
    if (!seenEventsObject) {
      SeenEvents.insert({ userid: Meteor.userId(), seenEvents: {} });
    } else {
      SeenEvents.update({ _id: seenEventsObject._id }, seenEventsObject);
    }
  },
});

It probably still won’t work until other points are addressed. Good luck! :slight_smile: