简体   繁体   English

防止重复插入文档

[英]Prevent duplicated document insertion

I'm building a web hook that will receive POST requests from Facebook. 我正在构建一个Web挂钩,它将接收来自Facebook的POST请求。 In each request, there's a facebookId field that will be used to insert a new record in database. 在每个请求中,都有一个facebookId字段,该字段将用于在数据库中插入新记录。 facebookId should be unique in the database (meaning no two records should have the same facebookId ). facebookId在数据库中应该是唯一的(意味着没有两个记录应具有相同的 facebookId )。 The prototype code is something like this 原型代码是这样的

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

The problem is, sometimes when there are many requests (yes, they have different meaning) containing the same new facebookId (which is not existed in the database) and they come almost at the same time . 问题是,有时当有许多请求(是的,它们具有不同的含义)包含相同的新 facebookId (数据库中不存在)并且它们几乎同时出现时 This will make the !Meteor.users.findOne({ facebookId }) check failed, and multiple records with same facebookId field will be inserted to the database. 这将使!Meteor.users.findOne({ facebookId })检查失败,并将具有相同facebookId字段的多个记录插入到数据库中。 How do I prevent this ? 我该如何预防呢?

You should create a unique index on your facebookId field to have MongoDB guarantee uniqueness across your data and then add some exception handling code around your the callback that your insert call returns (documentation here ). 您应该在facebookId字段上创建一个唯一索引 ,以使MongoDB保证数据之间的唯一性,然后在您的insert调用返回的回调周围添加一些异常处理代码( 在此处提供文档)。 You will need to judge based on your business requirements what the right exception handling code should look like. 您将需要根据业务需求判断正确的异常处理代码应该是什么样。

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' */
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM