蒙戈DBREF附加字段中mongoshell无形。 如何显示呢?(Mongo dbref add

2019-10-17 16:01发布

背景:这个问题提出了原则ODM,使用在一个DBREFS场_doctrine_class_name是在蒙戈外壳(2.2.2)无形的,引起了不小的罪魁祸首,当我们不得不手动更新记录。

例:

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()方法。 我还没有找到找到任何可用的改性剂()(尝试:指定者,的toJSON,printjson,的toString,六角,BASE64,漂亮,健谈,详细......)。

有没有人得到了在蒙戈外壳冗长显示DBREF内容的方法?

Answer 1:

蒙戈外壳是一个扩展的Mozilla的SpiderMonkey (1.7?),并有很简陋的功能。

从建议的外壳MongoDB的博客文章是定义如下inspect函数.mongorc.js在你的home目录

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(', ') + ')';
};


文章来源: Mongo dbref additional fields are invisible in mongoshell. How to display them?