流星:如何自动填充存储在集合中其他字段中的数组长度的字段?

问题描述:

我有SimpleSchema/Collection2这样定义的集合:流星:如何自动填充存储在集合中其他字段中的数组长度的字段?

Schema.Stuff = new SimpleSchema({ 
    pieces: { 
     type: [Boolean], 
    }, 
    num_pieces: { 
     type: Number, 
    }, 

我怎样才能得到num_pieces到自动与pieces阵列每当有变化的长度填充?

我愿意使用SimpleSchema的autoValuematb33:collection-hookspieces可能会与很多运营商进行更改,例如$push,$pull,$set,可能更多的是Mongo必须提供的,我不知道如何应对这些可能性。理想情况下,更新后只需查看pieces的值,但如何在不进入collection-hook的无限循环的情况下做出更改并进行更改?

下面是你会怎么做,防止无限循环“更新后”的集合挂钩的例子:

Stuff.after.update(function (userId, doc, fieldNames, modifier, options) { 
    if((!this.previous.pieces && doc.pieces) || (this.previous.pieces.length !== doc.pieces.length) { 
    // Two cases to be in here: 
    // 1. We didn't have pieces before, but we do now. 
    // 2. We had pieces previous and now, but the values are different. 
    Stuff.update({ _id: doc._id }, { $set: { num_pieces: doc.pieces.length } }); 
    } 
}); 

注意this.previous,您可以访问以前的文档,doc是当前文档。这应该足以完成其余的案例。

+0

只是一个失踪的,如果关闭托架,否则工作的魅力 - 谢谢! – Alveoli

你也可以这样做是正确的架构

Schema.Stuff = new SimpleSchema({ 
    pieces: { 
    type: [Boolean], 
    }, 
    num_pieces: { 
    type: Number, 
    autoValue() { 
     const pieces = this.field('pieces'); 
     if (pieces.isSet) { 
     return pieces.value.length 
     } else { 
     this.unset(); 
     } 
    }  
    }, 
}); 
+0

有人早些时候发布了相同的答案,现在已经删除了它。我试过这个,并且它不起作用,因为'pieces.value'引用了输入修饰符,例如“真”,而不是结果字段值,例如'[假,真,真]' – Alveoli