【问题标题】:selectively return a field depending on another field in MongoDB根据 MongoDB 中的另一个字段选择性地返回一个字段
【发布时间】:2017-02-01 20:56:32
【问题描述】:

我有一个收藏 - 类似于:

cmets: { 评论、所有者、匿名 }

文件可能是:

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

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

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

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

【问题讨论】:

  • 我在 MeteorJS 项目中运行这个服务器端。
  • 您的架构是否看起来像这样:{ comment "comment1", owner: "Frazer Kirkman", annonymous: false }, { comment "comment2", owner: "annonymous", annonymous: true } ?
  • 请参阅此链接,因为我认为您可以在 mongo 中排除顶级 _id 字段。参考这个链接->docs.mongodb.com/v3.2/tutorial/…
  • 嗨,谢尔盖,不,它看起来像:{ comment "comment1", owner: "Frazer Kirkman", annonymous: false }, { comment "comment2", owner: "Frazer", annonymous: true } - 这样所有者仍然可以编辑或删除它。

标签: mongodb meteor


【解决方案1】:

您可以创建一个聚合,其中根据匿名位填充所有者名称。您可以使用$cond 条件语句来做到这一点。

当您提供更多信息时,我可以帮助您完成声明。但请提供演示文件。

【讨论】:

  • 太棒了-我管理Comments.aggregate( [ { $project: { 'comment':1, 'owner': {$cond: { if: {$eq: ["$publiclyShared",true] }, then: "$owner", else: '' } } } } ] )-在需要时返回所有者:""。谢谢 :) 顺便说一句,你知道如何不包括所有者,而不是包括一个空字符串吗?
【解决方案2】:

这是 HoefMeistert 建议的示例

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2017-03-03
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多