Reputation: 2360
I'm writing a script for the mongo shell to populate some data for test.
I have two collections: club
, and team
, and in the team's document, it has a objectId reference to the club.
What I did is as following:
db.club.drop();
var club_1_id;
db.club.insert({name:'Club 1',
venue:'Somewhere'},
function(err, doc){
club_1_id=doc._id;
});
db.team.drop();
var team_1_id;
db.team.insert({name:'Team 1', club:{id: club_1_id, name: 'Club 1'}},
function(err, doc){
team_1_id=doc._id;
});
I'm actually not so surprised to see that in the team document, the club's ID is inserted to be null
, cause the call-back function may not be called in a timely fashion.
So in this case how can I set the id right?
Upvotes: 1
Views: 467
Reputation: 12934
You could try something like:
db.club.drop();
var club_1_id = new ObjectId();
db.club.insert({_id:club_1_id, name:'Club 1',venue:'Somewhere'});
db.team.drop();
var team_1_id = new ObjectId();
db.team.insert({_id:team_1_id, name:'Team 1', club:{id: club_1_id, name: 'Club 1'}});
Upvotes: 2
Reputation: 3264
var club_doc = {
_id: ObjectId()
name:'Club 1',
venue:'Somewhere'
}
var id = club_doc._id;
db.club.insert(club_doc);
var team_doc = {
_id: ObjectId(),
name:'Team 1',
club:{
id: id,
name: 'Club 1'
}
}
var teamID = team_doc._id;
db.team.insert(team_doc);
Upvotes: 0