在 select Pouchdb 之后异步写入

Async write after select Pouchdb

我试图在将元素插入我的 bdd 之前检查它是否存在。 我必须这样做才能(将来)修改这个现有元素。

我在 Node 6.9.1 中使用 PouchDb 和 PouchDb-find。

其实我是这样做的:

for(var i = 0; i < 10;i++ ){
    (function(_count, _pdb){
      var count = _count;
      var db = _pdb;
      db.find({
        selector: {numeroCandidat: parseInt(results[count].no_apb)}
      }).then((result) => {
        if(result.docs.length != 0){
          console.log("l'étudiant existe");
        }else{
          console.log("l'étudiant n'existe pas");

          var etudiant = {
            "numeroCandidat": results[count].no_apb,
            "nom": results[count].nom,
            "numeroGroupe": "gr" + results[count].groupe,
            "filiere": results[count].libelle,
          };

          db.post(etudiant).then((response) =>{
            // handle response
            console.log("STUDENT CREATED");
          }).catch(function (err) {
            console.log(err);
          });
        }
      }).catch(function (err) {
      });
    })(i, this.pdb);
  };

但问题是:由于我的 select 查询的异步版本...如果一个元素存在两次,它会附加第二个 select 发生在第一个元素插入之前,我的数据库中有两次这个元素。我不知道怎么处理这个。

所以..我找到了解决方法! 只需创建一个我在写入数据库后递归调用的函数。 再见循环。

var createStudents = function(_count, _pdb, _students){
    if(_count >= 10) return;
    console.log(_count);
    var count = _count;
    var db = _pdb;
    var students = _students.slice(0);
    db.find({
      selector: {numeroCandidat: parseInt(students[count].no_apb)}
    }).then((result) => {
      if(result.docs.length != 0){
        console.log("l'étudiant existe");
        createStudents(++count,db,results);
      }else{
        var etudiant = {
          "numeroCandidat": students[count].no_apb,
          "nom": students[count].nom,
          "numeroGroupe": "gr" + students[count].groupe,
          "filiere": students[count].libelle,
          "etudiantComms": [
            {"commentaire": students[count].commentaire}
          ]
        };
        db.post(etudiant).then((response) =>{
          // handle response
          console.log("STUDENT CREATED");
          createStudents(++count,db,results);
        }).catch(function (err) {
          console.log(err);
        });
      }
    }).catch(function (err) {
    });
  }

  createStudents(0,this.pdb,results);