使用 nodejs、restify 和 mongoose 确保数据完整性

Ensure data integrity with nodejs, restify and mongoose

本文关键字:mongoose 确保 数据完整性 restify nodejs 使用      更新时间:2023-09-26

我正在编写一个分析应用程序,用于收集事件并将其与访问者相关联。

我的访客猫鼬模型如下:

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]
});

该 API 接受访客信息和活动的混合

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

当 restify 收到请求时,它会检查访问者是否存在,如果存在,则 ap 只需按如下方式推送事件:

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);
    });
});

通过使用这种方法,我触发了几个并发请求,我得到了重复的访问者,而不是一个具有多个事件的访问者。

如何解决此问题?最好的方法是什么?

在猫鼬模型中的标识符上添加一个唯一索引。这样,第二个请求将中断唯一索引冲突。只要确保处理该错误即可。

如果您在客户端使用单页框架(角度、主干等),请确保在进行 api 调用时禁用该按钮,并在服务器响应时启用它。