thorus
June 20, 2017, 8:58am
1
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?
msavin
June 20, 2017, 9:33am
2
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
});
thorus
June 20, 2017, 9:36am
3
what to write here?= thenewId: what?
msavin
June 20, 2017, 9:46am
4
You just define the function call as a variable. I made a quick edit above to make it clearer.
thorus
June 20, 2017, 9:56am
5
I’m very new to meteor and mongodb 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?
thorus
June 20, 2017, 10:12am
7
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
msavin
June 20, 2017, 5:52pm
8
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.