1

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.

1 Answer 1

0

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 "=="

1
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
    – Tyler2P
    Jan 29, 2022 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.