【问题标题】:Prevent duplicated document insertion防止重复文档插入
【发布时间】:2018-04-11 14:33:02
【问题描述】:

我正在构建一个网络挂钩,它将接收来自 Facebook 的 POST 请求。在每个请求中,都有一个facebookId 字段,用于在数据库中插入一条新记录。 facebookId 在数据库中应该是唯一的(意味着没有两条记录应该有相同的 facebookId)。 原型代码是这样的

postRequestHandler(req) {
  const facebookId = req.body.facebookId;
  if (!Meteor.users.findOne({ facebookId })) {
    Meteor.users.insert({ 
      facebookId,
      // some other fields
    })
  }    
}

问题是,有时当有许多请求(是的,它们有不同的含义)包含相同的新 facebookId(数据库中不存在)并且他们来几乎同时。这将使!Meteor.users.findOne({ facebookId }) 检查失败,并且具有相同facebookId 字段的多条记录将被插入到数据库中。如何防止这种情况发生?

【问题讨论】:

标签: javascript node.js mongodb meteor duplicates


【解决方案1】:

您应该在您的facebookId 字段上创建一个unique index 以使MongoDB 保证您的数据的唯一性,然后在您的insert 调用返回的回调周围添加一些异常处理代码(文档here)。您将需要根据您的业务需求来判断正确的异常处理代码应该是什么样子。

Meteor.users.insert({ 
    facebookId,
    // some other fields
}, function(error, id) { 
    if ( error ) {
        /* add exception handling code here, e.g. return an error message to the client */
    } else {
        /* add code for successful case here, 'id' will be your newly inserted document's '_id' */
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 2016-02-19
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多