添加文档时,PouchDB 409冲突

PouchDB 409 conflict when adding doc.

本文关键字:冲突 PouchDB 文档 添加      更新时间:2023-09-26

在添加新文档时,我与pouchDB发生了奇怪的冲突。在创建新文档后不久创建新文档时,会出现冲突。然而,如果我等待5分钟左右,冲突就不再发生了。我对解决这个问题很感兴趣。

我正在使用带节点的express。下面是我添加项目的方法。它被用于路由器(见下文)

//require stuff
...
//require pouch
var PouchDB = require('pouchdb');
//db setup
var db = new PouchDB('http://127.0.0.1:5984/db');
module.exports = {
      addItem: (req, res, next) => {
        //check body fields with express validator
        req.checkBody('firstname', "Invalid, please enter firstname").notEmpty();
        req.checkBody('lastname', "Invalid, please enter lastname").notEmpty();
        req.checkBody('address', "Invalid, please enter address").notEmpty();
        var phonenumber = req.body.phonenumber; //phone number is optional dont use express validator
        var errors = req.validationErrors();
        if (errors) {
          res.render('add', {
            errors: errors
          });
        }
        var newDoc = {
          _id: date.toString() ,
          firstname: req.body.firstname,
          lastname: req.body.lastname,
          address: req.body.address,
          phonenumber: phonenumber,
          dateAdded: moment(date).format("dddd, MMMM Do YYYY, h:mm:ss a")
        }
        db.put(
          newDoc
        ).then(function (response) {
          res.redirect('/feed');
        }).catch(function (err) {
          if (err){
            return next(err);
          }
        });
      },
    ...
   //more methods
}
...
//export module

路由器添加

//require all the stuff
//post new item route
router.route('/feed/add').post(ActionController.addItem);

我使用了packdb -upsert来修复这个问题。https://github.com/pouchdb/upsert

并使用了puIfNotExists方法

...
    //save item to array and db
    db.putIfNotExists({
      _id: date.toString(),
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      address: req.body.address,
      phonenumber: phonenumber,
      dateAdded: moment(date).format("dddd, MMMM Do YYYY, h:mm:ss a")
    }).then(function () {
      return res.redirect('/feed');
    }).catch(function (err) {
      if (err) {
        return next(err);
      }
    })
...