添加doc时,PouchDB 409会发生冲突。

时间:2016-10-08 07:04:17

标签: javascript database express couchdb pouchdb

添加新文档时,我与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);

1 个答案:

答案 0 :(得分:0)

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