简体   繁体   中英

Create tags object from array in mongo collection for Select2 options

I have a mongo collection with a array field called 'tags'. What I want to do is create a single object that stores all of the various tags with a label and value. The end result should be an object I can use in a Select2 field in a Meteor application to create the results options. I have gotten close, but all of my solutions have not worked and are super ugly (read: not functional javascript)

Here is a sample document:

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

Now the end result I would like is:

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

Any ideas?

Here is the closest I have gotten.

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;
        }
      }

you can try with aggregation pipeline like this

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

Update. As soon as I posted I realized I simply need to add a inner loop. Its ugly, but it works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM