如何检查对象是否相似



以下是我的功能,用于检查会话中的用户名是否与最初发表评论的人匹配:

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
}

这就是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'
}
]
}

我用这种方式调用sameUser函数:

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

我不知道为什么变量";a";总是返回undefined,我安慰道。在for循环中记录两个id,它们显示相同的东西:

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

我调试并检查了它是否从未到达if条件之后的语句,不确定出了什么问题。

在此处找到解决方案:

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

显然,应该使用equals((而不是"来比较objectId==">

相关内容

最新更新