【问题标题】:Mongoose find unique tags猫鼬找到独特的标签
【发布时间】:2015-06-10 10:56:21
【问题描述】:

目前正在为每个用户保存一组标签。我遇到的问题是如何搜索唯一标签(所以我可以提前输入一个类型来添加新用户)现在如果我得到一个匹配项,该函数返回包含标签片段的整个标签数组,而不仅仅是匹配的用户的个人标签。

如何指定我只想返回唯一的标题值而不是整个标签数组?

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

【问题讨论】:

    标签: node.js mongodb mongoose mean-stack


    【解决方案1】:

    不断破解并想通了。此方案使用lodash_.filter 方法。

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

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2018-09-30
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-07
      • 2014-08-16
      相关资源
      最近更新 更多