how can I create my mongodb query based on the input from the user in node.js?

别来无恙 提交于 2019-12-10 16:02:37

问题


Currently in my app I store different forum posts. Users can add new messages and create new posts. Other users - while displaying the content - can filter it so that they will not see the content uploaded by specific users that they blocked earlier.

Each user is represented as a combination of device_id and display_name.

When users are fetching content, they do a post query and include an array of previously blocked users:

"blockedUsers": (
{
    "device_id" = "XXX";
    "display_name" = XXX;
},
{
    "device_id" = "YYY";
    "display_name" = YYY;
}
)

Currently there's a possibility of adding content with some registered display_name or anonymously.

Right now I support only filtering users with some display_name:

if(blockedUsers) {
    var excludedUsernames = [];

    for(var i in blockedUsers) {
         excludedUsernames.push(blockedUsers[i]['display_name']);
    }

    query.$and.push({ 'display_name': { $nin: excludedUsernames } });
}

That works fine - when user is registered and has some display_name (that is different than anonymous) - I don't care about his device_id, all I care is to block him by his display_name.

But, when some anonymous users has been blocked before:

"blockedUsers": (
{
    "device_id" = "XXX";
    "display_name" = "anonymous"; //represents anonymous user
},
{
    "device_id" = "YYY";
    "display_name" = "anonymous"; //represents anonymous user
}
)

I need to exclude his posts by device_id and the display_name == anonymous. In that case when there's some device_id but contains display_name != anonymous - I don't want to block that.

I don't know how to update my query so that it covers the requirement from above, could you help me with that? Thanks!


回答1:


If I understood well:

  • If user has a banned device_id, then block him
  • If user has a banned display_name, then block him

In that case, it does not really matter if he is anonymous or not.


let excludedUsernames, excludedDevices;

blockedUsers.forEach((e) => {
    excludedUsernames.puhs({ e["display_name"] });
    excludedDevices.push({ e["device_id"] });
});

query.$and.push({ 'display_name' : { $nin: excludedUsernames } });
query.$and.push({ 'device_id'    : { $nin: excludedDevices   } });

EDIT

query.$or.push({
    $and: [
        { 'device_id'    : { $nin: excludedDevices }},
        { 'display_name' : "anonymous" }
    ]
});
query.$or.push({ 'display_name' : { $nin: excludedUsernames } });


来源:https://stackoverflow.com/questions/41071134/how-can-i-create-my-mongodb-query-based-on-the-input-from-the-user-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!