如何使用lodash过滤mongoose中的结果

时间:2016-08-29 23:03:19

标签: javascript node.js lodash meanjs

我想只显示分配用户的合作伙伴,我有一个合作伙伴列表如下:

    { 
        "_id" : ObjectId("57c1cfa16c9cdc9007b26f8a"), 
        "__t" : "Partner", 
        "createdAt" : ISODate("2016-08-27T17:36:33.648+0000"), 
        "updatedAt" : ISODate("2016-08-27T17:36:33.648+0000"), 
        "user" : ObjectId("57c1cf776c9cdc9007b26f7b"), 
        "descr" : "asdkalksdasdasd", 
        "name" : "partner1", 
        "__v" : NumberInt(0)
    },{ 
       "_id" : ObjectId("57c1cfe76c9cdc9007b26fd2"), 
       "__t" : "Partner", 
       "createdAt" : ISODate("2016-08-27T17:37:43.784+0000"), 
       "updatedAt" : ISODate("2016-08-27T17:37:43.784+0000"), 
       "user" : ObjectId("57c1cf776c9cdc9007b26f7b"), 
       "descr" : "sdfdsfsdf", 
       "name" : "partner2", 
       "__v" : NumberInt(0)
   }

在我的用户模型中,我有这个:

  partners: {
        type: [{
            type: Schema.ObjectId,
            ref: 'Partner'
        }]
    },

我展示合作伙伴的功能如下所示:

/**
 * List of Partners
 */
exports.list = function (req, res) {
    // TODO:: Show only partners that user belongs to, except for admin, show all!
    Partner.find().sort('-created').populate('user', 'displayName').exec(function (err, partners) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
             partners = partners.filter(function(partner) {
               return _.includes(req.user.partners, partner._id);
             });

             res.jsonp(partners);
        }
    });
};

这根本不显示任何合作伙伴。

1 个答案:

答案 0 :(得分:0)

我不熟悉moongoose,但看起来你应该使用的代码应该是:

partners = partners.filter(function(partner) {
    // Check if any of the user's partners has the
    // same ID with the current partner's ID
    return req.user.partners.some(function(userPartner) {
        return userPartner._id === partner._id;
    });
});