1

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...

1

2 Answers 2

8

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);
});
Sign up to request clarification or add additional context in comments.

6 Comments

When I add you line I get this output: record contents [object Object]...why doesn't records just give me the document? I have seen many examples with the same code and they don't return any errors.
Answer edited. Its npm mongodb library implementation which give you this results. alternatively you can use npm mongoose which is wrapper over mongodb npm. It will give you desired results, more info here
With your stringify code I get this (same as if I were to use insertOne): { "ok": 1, "n": 1 }
@user2285490 mongoose is much more than just a wrapper. It's a great library, but perhaps a bit overkill just to get the desired result :-) The inserted document is available through records.ops, as you suggest.
sorry guys...so why cant records access the name field?
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.