cmonkey
cmonkey

Reputation: 13

Node.js / Mongodb insert callback returning undefined

when I run the simple code below to insert a new document:

collectionUsers.insert({'name':'john'},function(err,records){
    if (err) throw err;
    console.log("Id of new document added =  " + records[0]._id);
});

I get the following errors:

catch(err) { process.nextTick(function() { throw err}); }
                                             ^
TypeError: Cannot read property '_id' of undefined

Doesn't the callback function return an array? I'm just trying to get the id of the new document and save it in a variable for future use. Thanks for your help.

Alternatively, if I use insertOne instead, I get this output: Id of new document added = {"ok":1,"n":1}

But I want to use insert...

Upvotes: 1

Views: 4831

Answers (2)

cmonkey
cmonkey

Reputation: 13

Thanks a lot user2285490 and robertklep. I finally realized what the ops object in record is. This is the api documentation for future reference:

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#~insertWriteOpCallback

Upvotes: 0

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

There is ops object in records which contains inserted doc/docs.

Try:

collectionUsers.insert({'name':'john'},function(err,records){
   // You can explore more here
   console.log("record contents",JSON.stringify(records,null,4));
   // Desired output
   console.log("Id of new document added =  " + records.ops[0]._id);
});

Upvotes: 8

Related Questions