我正在使用mongodb(v2.6.7)和mongo(2.6.7)shell客户端。
我正在尝试使用insert和update命令返回的WriteResult对象。
根据mongodocs出现错误,它返回一个带有writeError子文档的writeResult对象。但我无法在shell或mongo的javascript文件中访问此子文档。
以下是我的问题的说明。
有人可以解释为什么会发生这种情况以及正确的方法。
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"]
答案 0 :(得分:7)
我不知道为什么以这种方式实现,但要访问包含的writeError
子文档,请在getWriteError()
对象上调用WriteResult
:
> 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
我无法找到任何相关文档。我在shell中输入writeResult.
后点击 Tab 两次就知道了,看看有什么可用。
答案 1 :(得分:0)
除了使用方法获取已经提到的WriteError对象之外,您还可以获得原始响应并对其进行处理:
> writeResult.getRawResponse()
{
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: foo.bar.$_id_ dup key: { : ObjectId('54cf8152733aa5e886f0e400') }",
"op" : {
"_id" : ObjectId("54cf8152733aa5e886f0e400"),
"a" : 1
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}
所以,你可以做这样的事情,事情会更加一致:
> raw = writeResult.getRawResponse();
> raw.writeErrors[0].errmsg
insertDocument :: caused by :: 11000 E11000 duplicate key error index: foo.bar.$_id_ dup key: { : ObjectId('54cf8152733aa5e886f0e400') }
> printjson(raw.writeErrors[0])
{
"index" : 0,
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: foo.bar.$_id_ dup key: { : ObjectId('54cf8152733aa5e886f0e400') }",
"op" : {
"_id" : ObjectId("54cf8152733aa5e886f0e400"),
"a" : 1
}
}
> JSON.stringify(raw.writeErrors[0])
{"code":11000,"index":0,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: foo.bar.$_id_ dup key: { : ObjectId('54cf8152733aa5e886f0e400') }"}