We use both the collection2 and the collection-hooks packages inside of our meteor application. That currently causes an infinite loop after an document is inserted or updated. We use Collection2’s autovalue
to set/update things like createdAt
and updatedAt
like shown below.
An excerpt from the document schema:
createdAt: {
type: String,
label: "The date this document was created.",
autoValue() {
if (this.isInsert) return (new Date()).toISOString();
},
},`
After an document is updated or inserted we need to geocode an address to coordinates and store them. For that we use collection-hooks.
An excerpt from the document hooks:
Documents.after.insert((async (userId, doc) => {
const documentId = doc._id;
const address = doc.address;
const result = await geocoder.geocode(`${address.street} ${address.zip} ${address.city} ${address.country}`)
.then((res) => {
// Log geocoder result when in development env
if (Meteor.isDevelopment) console.log(res); // eslint-disable-line
return res;
})
.catch((exception) => {
throw new Meteor.Error("500", exception);
});
Documents.update(documentId, {
$set: {
"coordinates.lat": result[0].latitude,
"coordinates.lon": result[0].longitude,
},
}, {
validate: false,
});
}));
Unfortunately does this approach cause an infinite loop. After you update or insert a document the hook gets triggered which then I guess triggers again the autovalue
and so on…
Has anyone any suggestion how I can fix or improve this?