Mongoose find unique tags

867 Views Asked by At

Currently saving an array of tags for each user. The issue I'm running into is how to search for unique tags (so I can do a type ahead for adding new users) Right now if I get a match, the function returns the WHOLE tags array that contain the tag fragment rather than just the individual tag of the user that matches.

How do I specify that I only want to return unique title values rather than the whole tag array?

var UserSchema = new Schema({
    username: {
        type: String,
        trim: true
    },

    tags:[
        {
        title:String
        }
    ]
});


exports.searchByTag = function(req, res) {
    var tag = req.params.tag;

        User.find({'tags.title':{ $regex: tag }}).distinct('tags.title', function(error, tags) {
        res.json(tags);
});
1

There are 1 best solutions below

1
On

Kept cracking & figured it out. This solution uses the lodash _.filter method.

    searchTerm = 'abc'
    //search the database for unique user.tag.title 
    User.find().distinct('tags.title', function(error, tagTitles) {

        var results = _.filter(tagTitles, function(title){ 
                //use lodash to filter out the the tagTitles array built by mongoose
                //return  = push the item into the results array based on regex match of searchTerm
                return title.match(searchTerm);
            });
        //respond with the results array
        res.json(results);
    });