I am using mongodb (v2.6.7) and mongo (2.6.7) shell client.
I am trying to use the WriteResult object returned by the insert and and update commands.
According to mongodocs in case of error it returns a writeResult object with writeError subdocument. But I am not able to access this subdocument in shell or in mongo's javascript file.
Below is an illustration of my problem.
- I insert an object and get the successful writeResult.
- Then I am inserting again with the same _id and I am getting the writeResult correctly printed on the screen which has "writeError" correctly set.
- Also the writeResult object seems to contain the writeError when I print it with printjson() method
- But when I print it with JSON.stringify() then I am not able to see the "writeError".
- Also writeResult.writeError is coming as undefined so I am not able to access its writeResult.writeError.code property.
Can someone please explain why is this happening and what is the correct way.
afv:PRIMARY>writeResult=db.sysinfo.insert({_id:"myid",otherData:"otherDataValue"}) WriteResult({ "nInserted" : 1 }) afv:PRIMARY>writeResult=db.sysinfo.insert({_id:"myid",otherData:"otherDataValue"}) WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: afvadmin.sysinfo.$_id_ dup key: { : \"myid\" }" } }) afv:PRIMARY> printjson(writeResult) { "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: afvadmin.sysinfo.$_id_ dup key: { : \"myid\" }" } } afv:PRIMARY> JSON.stringify(writeResult); {"nInserted":0,"nUpserted":0,"nMatched":0,"nModified":0,"nRemoved":0} afv:PRIMARY> writeResult.writeError afv:PRIMARY> writeResult.nInserted 0 afv:PRIMARY> writeResult.writeError.code 2015-02-02T16:34:42.402+0530 TypeError: Cannot read property 'code' of undefined afv:PRIMARY> writeResult["writeError"]