2013-01-31 19 views
1

背景:Doctrine ODM遇到了這個問題,它在DBRefs中使用了一個_doctrine_class_name字段,這個字段在Mongo shell(2.2.2)中是不可見的,並且當我們不得不手動更新一條記錄時會導致一個罪魁禍首。Mongo dbref其他字段在mongoshell中不可見。如何顯示它們?

例子:

mongoshell> use testdb; // for safety 
mongoshell> a = DBRef("layout_block", ObjectId("510a71fde1dc610965000005")); // create a dbref 
mongoshell> a.hiddenfield = "whatever" // add a field that's normally not there like Doctrine does 
mongoshell> a // view it's contents, you won't see hiddenfield 
mongoshell> for (k in a) { var val = a[k]; print(k + "(" + typeof(val) + "): " + val); } // you can see that there's more if you iterate through it 
mongoshell> db.testcoll.save({ref: [ a ]}) // you can have it in a collection 
mongoshell> db.testcoll.findOne(); // and normally you won't see it 

沒有從低於(或MongoVue)之類的第三命令迭代,你永遠不會知道在DBREF更還有,如果你簡單地使用find()。我還沒有找到find()的任何可用修飾符(嘗試:toArray,tojson,printjson,toString,hex,base64,pretty,chatty,verbose,...)。

有沒有人有辦法在mongo shell中詳細地顯示DBRef內容?

回答

2

Mongo shell是Mozilla SpiderMonkey(1.7?)的擴展,具有相當的骨骼功能。

MongoDB blog post on the shell的建議是在你的home目錄來定義.mongorc.js以下inspect功能

function inspect(o, i) { 
    if (typeof i == "undefined") { 
     i = ""; 
    } 
    if (i.length > 50) { 
     return "[MAX ITERATIONS]"; 
    } 
    var r = []; 
    for (var p in o) { 
     var t = typeof o[p]; 
     r.push(i + "\"" + p + "\" (" + t + ") => " + 
       (t == "object" ? "object:" + inspect(o[p], i + " ") : o[p] + "")); 
    } 
    return r.join(i + "\n"); 
} 

此外,您可以重新定義DBRef.toString功能是這樣的:

DBRef.prototype.toString = function() { 
    var r = ['"$ref": ' + tojson(this.$ref), '"$id": ' + tojson(this.$id)]; 
    var o = this; 
    for (var p in o) { 
     if (p !== '$ref' && p !== '$id') { 
      var t = typeof o[p]; 
      r.push('"' + p + '" (' + t + ') : ' + 
       (t == 'object' ? 'object: {...}' : o[p] + '')); 
     } 
    } 
    return 'DBRef(' + r.join(', ') + ')'; 
}; 
+1

自此(2.4.x)Greasmonkey已更改爲V8。現在可以使用JSON.stringify()來代替.toSource()或tojson()。請參閱:http://docs.mongodb.org/manual/release-notes/2.4-javascript/ – Andor

相關問題