如何定义条件“字段选择”在 mongodb 中“find()”询问?

发布于 12-11 09:59 字数 836 浏览 1 评论 0原文

是否可以有条件地指定查询返回的字段。这是我的用例:我有一个带有嵌套用户对话的对象,如下所示:

{
  "_id" : "someId",
  user_id: 'user1',
  conversations: 
  [ 
    { 
      user_id: 'user2',
      comments: 
      [    
        { 
          user_id: 'user2',
          text: 'Hi user1' 
        },
        { 
          user_id: 'user1',
          text: 'Hi user2' 
        },
      ] 
    }, 
    { 
      user_id: 'user3',
      comments: 
      [    
        { 
          user_id: 'user3',
          text: 'Hi user1' 
        }
      ]
    }, 
  ]
}

我希望允许所有用户搜索和查看所有对象,但不允许他们不拥有的对话。内容如下:

findObj = function(criteria, user, callback) {
    Object.find({criteria}, {conversation: 
       {
          if (user_id == user.id || conversations[].user_id = user.id) {1} else {0} 
       } }
    );
}

预先感谢您的帮助, -埃里克

Is it possible to conditionally specify the fields returned by the query. Here is my use case: I have an object with nested user conversations as follows:

{
  "_id" : "someId",
  user_id: 'user1',
  conversations: 
  [ 
    { 
      user_id: 'user2',
      comments: 
      [    
        { 
          user_id: 'user2',
          text: 'Hi user1' 
        },
        { 
          user_id: 'user1',
          text: 'Hi user2' 
        },
      ] 
    }, 
    { 
      user_id: 'user3',
      comments: 
      [    
        { 
          user_id: 'user3',
          text: 'Hi user1' 
        }
      ]
    }, 
  ]
}

I would like to allow all users to search for and view all objects but not conversations they don't own. Something as follows:

findObj = function(criteria, user, callback) {
    Object.find({criteria}, {conversation: 
       {
          if (user_id == user.id || conversations[].user_id = user.id) {1} else {0} 
       } }
    );
}

Thanks in advance for your help,
-Eric

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落日海湾2024-12-18 09:59:14

您可以获取所有与用户 X 进行对话的用户,如下所示:

db.users.find({$or:[{user_id: X}, {'conversations.user_id':x}]})

但这不会执行您想要的操作。您的架构遇到了问题。您必须从用户对象中删除对话并将它们存储在专用集合中,该集合允许单独查询特定对话。

You can get all users that have conversations that involve user X like so :

db.users.find({$or:[{user_id: X}, {'conversations.user_id':x}]})

However this will not do what you want. You're running into a problem with your schema. You have to remove conversations from the user objects and store them in a dedicated collection that allows for queries on specific conversations seperately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文