首页 > 解决方案 > 在feathersjs应用程序之外编辑数据库时如何更新客户端

问题描述

我有两个服务器端应用程序编辑同一个数据库。

一个服务器是一个feathersjs 应用程序,另一个是一个简单的nodejs 应用程序。前端应用程序通过 feathersjs 客户端连接到 feathersjs 应用程序。

当 nodejs 应用程序编辑数据库时,如何更新连接到 feathersjs 应用程序的客户端?由于目前在featherjs 应用程序之外所做的任何更改都不会反映在featherjs 客户端上。

我可以以某种方式触发修补事件并强制客户端下拉更新的数据吗?

标签: javascriptfeathersjs

解决方案


如果您将 mongodb 与 WiredTiger storageEngine 一起使用,您可以使用 collection.watch() 函数并在您的羽毛应用程序中添加一个监视器,如下所示

   //src/services/monitor.js 
   module.exports = function(app){
      //get mongo client
      const mongoClient = app.get('mongoClient');
      //connect db
      mongoClient.then(db => {

        //collection to watch
        const collection = db.collection('your_collection_name')

        //watch collection
        const changeStream = collection.watch({ fullDocument: 'updateLookup' });

        //on some data changed
        changeStream.on('change', data => {
          console.log ( 'something is changed in your collection' , data )
          //your service.emit
        });
      })
    }

然后我添加了这个简单的监视器/src/services/index.js(也许不是正确的方式,但它有效)

//src/services/index.js
...
const monitor = require('./monitor.js');
module.exports = function (app) {
   ...
   app.configure(monitor);
   ...
}; 

集合每次更改时返回的数据

{ _id:
   { _data:
      '825C7F03230000001C29295A100490DEF2C65812410FABF0DE46F9C89D7246645F696400645C1AC097B189CBD5D4A24D330004' },
  operationType: 'replace',
  clusterTime:
   Timestamp { _bsontype: 'Timestamp', low_: 28, high_: 1551827747 },
  fullDocument:
   { _id: 5c1ac097b189cbd5d4a24d33,
     id: '12',
     language: 'it-IT',
     category: 'some data',
     slug: '',
     description: 'some data',
     src:'',
     color: 'card',
     status: true,
     home: true,
     order_int: '3',
     visual: 'card' },
  ns: { db: 'mydb', coll: 'mycollection' },
  documentKey: { _id: 5c1ac097b189cbd5d4a24d33 } }

更多信息在这里https://docs.mongodb.com/manual/reference/method/db.collection.watch/


推荐阅读