如何定义条件“字段选择”在 mongodb 中“find()”询问?
是否可以有条件地指定查询返回的字段。这是我的用例:我有一个带有嵌套用户对话的对象,如下所示:
{
"_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
您可以获取所有与用户 X 进行对话的用户,如下所示:
但这不会执行您想要的操作。您的架构遇到了问题。您必须从用户对象中删除对话并将它们存储在专用集合中,该集合允许单独查询特定对话。
You can get all users that have conversations that involve user X like so :
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.