NB: Esta es la primera función de JavaScript que he escrito. Mi pregunta está inspirada en otra pregunta sobre el descenso recursivo dentro de un documento MongoDB.
Probé la función en jsfiddle.net y funciona, pero cuando la pruebo en mongoplayground.net , no funciona.
Colección de entrada:
[ { "_id": 0, "text": "Node1", "children": [ { "text": "Node2", "children": [] }, { "text": "Node3", "children": [ { "text": "Node4", "children": [ { "text": "Node5", "children": [] }, { "text": "Node6", "children": [] } ] }, { "text": "Node7", "children": [] } ] } ] } ]Tubería de agregación de mongoplayground.net:
db.collection.aggregate([ { "$set": { "texts": { "$function": { "body": "function(t, n) {function drill(t, n) {if (n.length > 0) {for (let elem of n) {t.push(elem.text); drill(t, elem.children)}} return t};drill(t,n)}", "args": [ [ "$text" ], "$children" ], "lang": "js" } } } } ]) jsfiddle.net genera el resultado deseado, ["Node1", "Node2", "Node3", "Node4", "Node5", "Node6", "Node7"] , pero mongoplayground.net establece "texts" en null .
¿Hay alguna forma de arreglar la "$function" MongoDB o es una limitación de mongoplayground.net o MongoDB?
¿Qué tal simplemente eliminar la función externa para obtener los resultados deseados?
db.collection.aggregate([ { "$addFields": { "texts": { "$function": { "body": "function drill(t, n) {if (n.length > 0) {for (let elem of n) {t.push(elem.text); drill(t, elem.children)}} return t};", "args": [ [ "$text" ], "$children" ], "lang": "js" } } } } ])Puedes ver que funciona aquí