Home > OS >  How do I check if the objectids are similar?
How do I check if the objectids are similar?

Time:02-03

Below is my function to check if the username in session matches to the person who commented originally:

async sameUser(id,uname){
        const blogsCollection = await blogs();
        id = ObjectId(id)
        let a;
        const finder = await blogsCollection.findOne({'comments._id':id});
        for(i=0;i<finder.comments.length;i  ){
              if (finder.comments[i]._id == id) {
                a = finder.comments[i].commentuser;
              }
            }
        if (a == uname) return true
        else return false
        }

This is what the collection looks like in MongoDB:

{
  _id: new ObjectId("61f4c62818c9c4633a117beb"),
  title: 'my first blog',
  body: 'wazzzzzzzzzzzzzzzzzzup',
  bloguser: {
    _id: new ObjectId("61f22f8bb5c180195ca925df"),
    username: 'tom'
  },
  comments:  [{
      _id: new ObjectId("61f4ec0a0d4c9731bdbe5f6b"),
      comment: 'wow',
      commentuser: 'tom'
    }
  ]
}

I am calling the sameUser function this way:

const user = await blogs.sameUser('61f4ec0a0d4c9731bdbe5f6b','tom');
console.log(user); 

I don't know why variable "a" always returns undefined, I consoled.log both the ids in the for loop and they display the same thing:

new ObjectId("61f4ec0a0d4c9731bdbe5f6b")
new ObjectId("61f4ec0a0d4c9731bdbe5f6b")

I debugged and checked that it never reaches the statement after the if condition, not sure what's wrong.

CodePudding user response:

Found solution here:

https://whitehorsesblogarchive.wordpress.com/2017/10/15/how-to-compare-mongo-_ids-in-javascript/

Apparently comparing objectIds should be done using equals() instead of "=="

  •  Tags:  
  • Related