0

I'm writing an analytics application that collects events and associates it with visitors.

My Visitor mongoose model as follows:

var visitorSchema = new Schema({ 
    created_at: { type: Date, default: Date.now }, 
    identifier: Number,
    client_id: Number,
    account_id: Number,
    funnels: [String],
    goals: [Goal],
    events: [Event]
});

The api accept a mixed of visitor info and the event

{
  "identifier": 11999762224,
  "client_id": 1,
  "account_id": 1,
  "event": {
      "context": "Home",
      "action": "Click red button",
      "value": ""
  }
}

When restify receives a request it checks if the visitor exists, and if it exists the ap just push the event as follows:

server.post('/event', function (req, res, next) {
    Visitor.findOne({ 
        identifier: req.params.identifier, 
        client_id: req.params.client_id,
        account_id: req.params.client_id
    }, function(err, visitor) {
        if(err) {
                             console.log(err);
            res.send(500, visitor);
        }

        if(visitor) {
            visitor.events.push(req.params.event);
            visitor.save();
        } else {
            visitor = new Visitor({
                identifier: req.params.cpf, 
                client_id: req.params.client_id,
                account_id: req.params.client_id,
                funnels: req.params.funnels,
                events: req.params.event
            });
            visitor.save();
        }

        res.send(200, visitor);
    });
});

By using this method, and I trigger several concurrent requests I get duplicated visitors instead of one visitor with multiple events.

How can I solve this issue? Whats the best approach?

Guilherme Viebig
  • 6,901
  • 3
  • 28
  • 30

1 Answers1

0

Add a unique index on identifier in mongoose model. This way the second request will break with unique index violation. Just make sure you handle that error.

If you are using single page framework on the client side (angular, backbone etc) make sure you disable the button when you make an api call, and enable it on server response.

J.D.
  • 1,145
  • 2
  • 15
  • 29