Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB weird writeResult behaviour

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"]

like image 959
Nitiraj Avatar asked Feb 12 '23 00:02

Nitiraj


1 Answers

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.

like image 185
JohnnyHK Avatar answered Feb 23 '23 16:02

JohnnyHK