I have a collection defined with SimpleSchema/Collection2 like this:
Schema.Stuff = new SimpleSchema({
pieces: {
type: [Boolean],
},
num_pieces: {
type: Number,
},
How can I get num_pieces
to automatically be populated with the length of the pieces
array whenever there is a change?
I am open to using SimpleSchema's autoValue
or matb33:collection-hooks
. pieces
could potentially be changed with quite a few operators, such as $push
, $pull
, $set
, and probably more that Mongo has to offer, and I had no idea how to cope with these possibilities. Ideally one would just look at the value of pieces
after the update, but how can you do that and make a change without going into a bit of an infinite loop on the collection-hook?
Here's an example of how you'd do a collection hook 'after update' that prevents the infinite loop:
Note that
this.previous
gives you access to the previous document, anddoc
is the current document. This should give you enough to finish the rest of the cases.