PouchDB 使用 .put() 给出 409 "Document update conflict" 错误,即使使用正确的 ._rev

PouchDB gives 409 "Document update conflict" error with .put(), even with correct ._rev

我有一个函数可以在 PouchDB 中创建或更新文档,如下所示。该功能在第一次 运行 时完美运行。但是,每个后续 运行 都会产生 409 错误,即使 ._rev 属性 看起来是正确的。

function saveEventMatchesToDatabase(event, db) {
    /* event: An event object from The Blue Alliance API. */
    /* db: a reference ot the PouchDB database. */

    /* Purpose: Given an event, extract the list of matches and teams, and save them to the database. */
    TBA.event.matches(event.key, function(matches_list) {
        var i = 0;
        for (i = 0; i < matches_list.length; i++) {
            var match = new Object();
            var docrec = new Object();

            match._id = 'matches/' + matches_list[i].key;
            match.redTeam = matches_list[i].alliances.red.teams;
            match.blueTeam = matches_list[i].alliances.blue.teams;

            /* If the doc already exists, we need to add the _rev to update the existing doc. */
            db.get(match._id).then(function(doc) {
                match._rev = doc._rev;
                docrec = doc;
            }).catch(function(err) {
                if ( err.status != 404 ) {
                    /* Ignore 404 errors: we expect them, if the doc is new. */
                    console.log(err);
                }
            });

            db.put(match).then(function() {
                // Success!
            }).catch(function(err) {
                console.log('\ndoc._rev: ' + docrec._rev);
                console.log('match._rev: ' + match._rev);
                console.log(err);
            });
        }
    });
}

运行第二次使用此函数的控制台输出示例如下。 match_list 中的每个项目都会出现同样的错误,而不仅仅是间歇性的。

doc._rev: 1-7cfa2c6245dd939d8489159d8ca674d9
match._rev: 1-7cfa2c6245dd939d8489159d8ca674d9
r {status: 409, name: "conflict", message: "Document update conflict", error: true}

我不确定我错过了什么,这导致了这个问题。非常感谢任何关于下一步去哪里的建议。

第一个问题似乎是您在循环中使用函数,这意味着内部函数内部使用的任何变量都会根据调用函数的时间随机变化。您可以使用 forEach().

而不是 for 循环

然而,第二个问题是你没有正确使用promise;在执行 put() 之前,您需要等待 get() 的结果。所以可能 forEach() 一开始就不是你想要的;你可能想使用 Promise.all() 然后编写你的承诺。

前一段时间我写过一篇关于这个的文章;许多人告诉我,尽管它很长,但它值得一读:"We have a problem with promises." 阅读它,你应该希望在它结束时理解 promises。 :)