How to filter MongoDB object list in express-node app


MongoDB objects are object Id of another document stored in the mongo database. We can place multiple objects using list of object fields. A sample mongo object list as follows.

 "tags": [
        {
            "posts": [
                "5fef1f5087a69346300003a7"
            ],
            "_id": "5fef1f5187a69346300003a8",
            "tagName": "Test",
            "createdAt": "2021-01-01T13:10:41.799Z",
            "updatedAt": "2021-01-01T13:10:41.855Z",
            "__v": 1
        },
        {
            "posts": [
                "5fef1f5087a69346300003a7"
            ],
            "_id": "5fef1f5187a69346300003a9",
            "tagName": "VM",
            "createdAt": "2021-01-01T13:10:41.804Z",
            "updatedAt": "2021-01-01T13:10:41.896Z",
            "__v": 1
        },
        {
            "posts": [
                "5fef1f5087a69346300003a7",
                "5fef1f7287a69346300003af"
            ],
            "_id": "5fef1f5187a69346300003aa",
            "tagName": "JS",
            "createdAt": "2021-01-01T13:10:41.810Z",
            "updatedAt": "2021-01-01T13:11:15.561Z",
            "__v": 2
        }
    ],

We want to lookup at the above list of tags and make sure no more duplicate tags shown up in the future. A loop will do the job, using a filter we can do the same.

if (post.tags.filter(xtag => xtag == 'ABCD') == false) {
console.log(`No Tag found`);
} else {
console.log(`Tag already added`);
}

The filter uses a quick arrow function to filter result and return false when it failed to match the tag.

Following Mongo posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.