Howto get the _id on insert to collection?

I’m creating categories where I need to get the _id for the document and insert it two places in the document: _id and thenewId (ARRAY)

 Categories.insert({
      thenewId: what?
      userid: Meteor.userId(),
      createdAt: new Date() // current time
    });
      

Howto get the _id when inserting?

This will make the code run synchronously and get you the _id of the document:

var newDoc = Categories.insert({
      thenewId: what?
      userid: Meteor.userId(),
      createdAt: new Date() // current time
    });

what to write here?= thenewId: what?

You just define the function call as a variable. I made a quick edit above to make it clearer.

I’m very new to meteor and mongodb :frowning: still dont understand how to get thenewId in the same document as the new _id

eg.

_id: EJWntSG6nWCZrG3x5
thenewId" : [ "EJWntSG6nWCZrG3x5" ],

Is there a reason why you need to do that?

I’m going to use the thenewId with sub categories

if in 3 sub levels down then :

_id: DJWntSG6nWCZrG3x5
thenewId" : [ “EJWntSG6nWCZrG3x5”,“AJWntSG6nWCZrG3x5”,DJWntSG6nWCZrG3x5" ],

Don’t know if it is wise but I will try it out

thenewId will be called parrentArray

so check this out…

var newDocID = Categories.insert({
      userId: Meteor.userId(),
      createdAt: new Date()
    });

the variable newDoc will give you back the _id of the document that you inserted.

Then, you can do whatever you want this it. In this case, we will add it to an array of ID’s of the user document.

Users.update({
   owner: userId
}, {
  $push: {
    categoryIds: newDocID
  }
}

It looks like what you are trying to do is make sure a document has multiple IDs? its probably better to to create a another collection to keep the array of IDs in it. The _id field, for one thing, ensures that no documents have the same ID. The strategy above can help you that.

Perfect, big thanks :slight_smile: