根据MongoDB中的另一个字段有选择地返回一个字段



我有一个集合 - 像这样:

评论:{ 评论, 所有者, 匿名 }

这些文件可能是:

{ comment "comment1", owner: "Frazer Kirkman", anonymous: false }, 
{ comment "comment2", owner: "Frazer Kirkman", anonymous: true }, 
{ comment "comment3", owner: "HoefMeistert", anonymous: true }.

我想始终发布评论,并且仅在匿名为假或用户是所有者时才发布所有者。

所以上面会为弗雷泽返回这个:

{ comment "comment1", owner: "Frazer Kirkman"}, 
{ comment "comment2", owner: "Frazer Kirkman"}, 
{ comment "comment3"}.

而这个给霍夫:

{ comment "comment1", owner: "Frazer Kirkman"}, 
{ comment "comment2"},
{ comment "comment3", owner: "HoefMeistert"}.

像这样:

Comments.find({},{'comment':1, 'owner':(anonymous || owner==thisUser)}}

您可以创建一个聚合,其中根据匿名位填充所有者名称。您可以使用 $cond 条件语句执行此操作。

当您提供更多信息时,我可以帮助您进行声明。但请提供演示文档。

以下是HoefMeistert建议的一个例子

Comments.aggregate([
    {},   // match all entries
    { $project: { "comment":true, 'owner':  { $cond: {  
          if: {$and:[{$eq: ["$anonymous",true]},
                     {$ne: ['$owner',this.userId]}
                    ] }, 
          then: '', else: '$owner'          }        } 
                 }
    }
]); 

最新更新