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.
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"]
I don't know why it was implemented this way, but to access the contained writeError
subdocument, you call getWriteError()
on a WriteResult
object:
> writeResult.getWriteError()
WriteError({
"index": 0,
"code": 11000,
"errmsg": "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test.$_id_ dup key: { : \"myid\" }",
"op": {
"_id": "myid",
"otherData": "otherDataValue"
}
})
> writeResult.getWriteError().code
11000
I couldn't find any documentation for this. I figured it out by hitting Tab twice after typing writeResult.
in the shell to see what's available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With