Node.js Sails.js/waterline自引用多对多双向关联

Node.js Sails.js/waterline自引用多对多双向关联,node.js,sails.js,waterline,Node.js,Sails.js,Waterline,我有以下类型的设置:我有一个名为Person的模型,它通过多对多关联与其他Person相关。这种解释是,一个人可以有许多邻居,一个人也可以是许多其他人的邻居。模型属性大致如下所示: ... attributes: { name: 'string', neigh: { collection: 'Person', via: 'neighOf', dominant: true }, neighOf: { c

我有以下类型的设置:我有一个名为
Person
的模型,它通过多对多关联与其他
Person
相关。这种解释是,一个人可以有许多邻居,一个人也可以是许多其他人的邻居。模型属性大致如下所示:

...
attributes: {
    name: 'string',
    neigh: {
        collection: 'Person',
        via: 'neighOf',
        dominant: true
    },
    neighOf: {
        collection: 'Person',
        via: 'neigh'
    }
}
...
现在想象我们有两个人,A和B。A是B的邻居,B是A的邻居。A搬走了,所以他们不再是邻居。现在,当我从A的鼻梁上移除B时,A不会自动从B的鼻梁上移除。这是一个问题

我试图通过为
Person
模型创建
afterUpdate
函数来解决这个问题,在这个函数中,我将检查A的
neighOf
字段中的每个人,看A是否仍然将他们作为邻居,如果没有,将更新不再是A邻居的
人员
。我也想做相反的事情,因此如果A再次成为B的邻居(例如,B的
neigh
字段已更新),A的
neigh
字段也应自动更新。以下是我的想法:

afterUpdate: function(updatedPerson, cb) {
    Person.findOne(updatedPerson.id)
        .populate('neigh')
        .populate('neighOf')
        .then(function(person) {
            updatedPerson = person;
            var ids = _.pluck(updatedPerson.neigh, 'id');
            return Person.find(ids).populate('neigh');
        })
        .then(function(people) {
            neigh_of_updated = people;
            var ids = _.pluck(updatedPerson.neighOf, 'id');
            return Person.find(ids).populate('neigh');              
        })
        .then(function(people) {
            neighOf_of_updated = people;
            var updates = [];
            _.forEach(neighOf_of_updated, function(person) {
                if (_.find(person.neigh, function(neigh) {return neigh.id === updatedPerson.id})
                    && !_.find(updatedPerson.neigh, function(neigh) {return neigh.id === person.id})) {
                    var neighIds = _.pluck(person.neigh, 'id');
                    _.remove(neighIds, function(id) {
                        return id === updatedPerson.id;
                    });
                    updates.push(Person.update(person.id, {neigh: neighIds}));
                }
            })
            return Promise.all(updates);
        })
        .then(function() {
            var updates = [];
            _.forEach(neighOfUpdated, function(person) {
                if (!_.find(person.neigh, function(neigh) { return neigh.id === updatedPerson.id; })) {
                    var neighIds = _.pluck(person.neigh, 'id');
                    neighIds.push(updatedPerson.id);
                    updates.push(Person.update({id: Person.id}, {neigh: neighIds}))
                }
            })
            return Promise.all(updates);
        })
        .then(function() {
            cb();
        })
        .catch(function(error) {
            cb(error);
        })
}
到目前为止,我还不能让这两个都工作。我可以让它们分开工作,但是当合并时,代码会因为一些更新发生在中间,导致新的和新的后续更新被调用。 我觉得这是一个非常常见的用例,所以我猜应该有一个更简单的方法来完成所有这些-或者如果没有,至少有一些方法可以让它工作。事实上,我觉得我的头撞到了砖墙上,这件事本应该是件容易的事。有没有人有过类似协会的经验,如何处理