Wudong
Wudong

Reputation: 2360

How to get the inserted document's ID in MongoDB

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

Answers (2)

Anand Jayabalan
Anand Jayabalan

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

user602525
user602525

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

Related Questions