javascript - 从 mongo 集合中的数组为 Select2 选项创建标签对象

标签 javascript mongodb meteor

我有一个带有名为“标签”的数组字段的 mongo 集合。我想要做的是创建一个单一的对象来存储所有带有标签和值的各种标签。最终结果应该是一个对象,我可以在 Meteor 应用程序的 Select2 字段中使用它来创建结果选项。我已经接近了,但是我所有的解决方案都没有用,而且非常丑陋(阅读:非功能性 javascript)

这是一个示例文档:

{
"_id":  "sjkjladlj",
"title": "Coldplay is Cool",
"tags": ["music", "yuppie"]
}

现在我想要的最终结果是:

[
{
value: "music",
label: "music"
},
{
value: "yuppies",
label: "yuppies"
},
{
value: "Some tag from another doc"
label: "Some tag from another doc"
}
]

有什么想法吗?

这是我得到的最接近的。

options: function() {
          tagsArray = [];
          ca = Notes.find({}, {tags: 1}).fetch();
          ca.forEach(function(it) {
            result = {};
            result = it.tags;
            tagsArray.push(result);
          });
          console.log(tagsArray);
          return tagsArray;
        }
      }

最佳答案

你可以试试这样的聚合管道

db.colleaction.aggregate([{$project:{_id:0,tags:1}},{$unwind:"$tags"},{$project:{"value":"$tags","lable":"$tags"}}])

关于javascript - 从 mongo 集合中的数组为 Select2 选项创建标签对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804979/

相关文章:

node.js - 通过 mongodb 和 mongoose 中的 id 删除对象

mongodb - 无法将filebeat输出发送到mongodb

javascript - meteor 模板更新

javascript - 当使用 AngularJS 登录后授权 header 不存在时,Spring Security 不会抛出错误

javascript - tinymce 不支持 React hook 形式

mongodb - PHP/MongoDB : pushing an array value into array field with the $pushAll modifier

javascript - 无法访问数据 : property in iron router 中的 this.params 变量

node.js - 在 AWS Opsworks 上设置使用 SSL 运行 Meteor 应用程序时遇到问题

javascript - Discord.js 发送表情符号

javascript - 显示正在单击的事件的数据