简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM