如何将对一个文档所做的更改传播到 mongodb 中的其他相关文档

How to propagate changes made to one doc, on to other related documents in mongodb

我有一个 meteor 应用程序,其中有一个观察器来帮助检测对某个特定文档的任何更改。如何将对该文档所做的更改传播到其他相关文档而无需编写多个通用查询?

我有:

组织策略:

{
    "_id" : "uudY4ekaZ4tPpN7KN",
    "organizationName" : "combat wombat systems 2",
    "priorityIP" : "2.2.2.2,6.6.6.6/24",
    "blacklistedServers" : "3.3.3.3",
    "policyType" : "orgLevelPolicy",

}

DeptLevelPolicy:

{
    "_id" : "Fb75pKgvePxakKTi4",
    "organizationName" : "combat wombat systems 2",
    "departmentName" : "mighty moose",
     "useOrgPolicyValuesForPriorityIp" : true,
    "priorityIP" : "2.2.2.2,6.6.6.6/24",
    "useOrgPolicyValuesBlacklistedServers" : true,
    "blacklistedServers" : "3.3.3.3",
    "policyType" : "departmentLevelPolicy",
}

我需要做什么

如果 orgLevelPolicy 文档更改,则仅更新那些 deptLevelPolicy 字段的相应布尔标志设置为 true

的文档

例如

如果orgLevelPolicy.priorityIP发生变化,则只更新deptLevelPolicydeptLevelPolicy.priorityIP的字段,其useOrgPolicyValuesBlacklistedServers设置为true

我有一个粗略的观察者,如下所示,但是对 orgPolicy 的任何更改都会触发对 all deptLevelPolicy 的大量更改,而不管它们的 bool 标志是否已设置,或者该字段是否发生了变化。

(我希望我的解释有意义。如果我需要进行任何更改以更好地说明场景,请告诉我)

 Meteor.startup(() => {

     var cursor = policies.find({
         policyType: "orgLevelPolicy"
     });

     var handle = cursor.observe({
         changed: function(orgLevelPolicyChanged) {
             console.log("Updating: departmentLevelPolicy: priorityIP");
             policies.update({policyType:"departmentLevelPolicy","useOrgPolicyValuesForPriorityIp": true},{$set:{priorityIP: orgLevelPolicyChanged.priorityIP, organizationName: orgLevelPolicyChanged.organizationName}},{multi:true});
             console.log("Updating: departmentLevelPolicy: blacklistedServers");
         },

     });
 });

你应该非常接近,但你试图在你的修饰符而不是你的查询中匹配上级组织。

.update() 的第一个参数中进行名称匹配(查询)而不是第二个参数(修饰符 )

const handle = cursor.observe({
  changed(orgLevelPolicyChanged) {  
    policies.update(
      {
        policyType: "departmentLevelPolicy",
        useOrgPolicyValuesForPriorityIp: true,
        organizationName: orgLevelPolicyChanged.organizationName
      },
      { $set:
        {
          priorityIP: orgLevelPolicyChanged.priorityIP,
        }
      },
      { multi:true }
    );
  },
 });