【问题标题】:PouchDB 409 conflict when adding doc.添加文档时 PouchDB 409 冲突。
【发布时间】:2017-02-17 04:30:57
【问题描述】:

添加新文档时,我与 pouchDB 发生了奇怪的冲突。在创建另一个文档后不久创建新文档时会出现冲突。但是,如果我等待约 5 分钟左右,冲突就不再发生。我非常坚持解决这个问题。

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

//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);

【问题讨论】:

    标签: javascript database express couchdb pouchdb


    【解决方案1】:

    我使用 pouchdb-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);
          }
        })
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      相关资源
      最近更新 更多