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?