Fred J. Fred J. - 3 months ago 6x
Javascript Question

How to save a Mongo document's own _id in a nested field?

This Meteor server code tries to copy the newly created property

into a sub document but failed to do so.

How can it be done?


The code uses

MyCollection.after.insert(function(userId, doc) {
if (doc.element === 'myString') {
doc.values[0]._id = doc._id;


Mutating the doc in the after hooks of matb33:collection-hooks will not cause additional queries to be run. You will need to explicitly update the document if you wish to do so.

However, in this particular case, if you really need the duplicate _id in the document, you could generate an _id and specify it when inserting the document.

You can probably use MyCollection._makeNewID() method, as this API has not changed for a few years and it is what the Mongo package uses internally.

const _id = MyCollection._makeNewID();
const doc = {
  values: [
    }, {