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
- How to add element to mongoose object array in Nodejs - How to add element to a mongodb object array
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- How to populate multiple MongoDB objects on the same path in express-node - How to populate multiple objects in MongoDB in the same path
- How to populate selected fields in a mongo document path in expressjs - How to populate object in mongo doc at a specific path with specific fields
- How to populate and display nested mongo objectin express-node route - How to populate object in express-MongoDB app
- How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
- How to render mongo document in Reactjs - How to render mongo document in react component
- How to filter MongoDB object list in express-node app - How to filter a mongo object list in document in express-node app
- How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
- How to create document using mongoose in express-node app - How to save MongoDB document to the collection using mongoose REST operations