【发布时间】:2022-01-29 16:57:08
【问题描述】:
以下是我检查会话中的用户名是否与最初评论的人匹配的功能:
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 循环中安慰.log 两个 id 并且它们显示相同的内容:
new ObjectId("61f4ec0a0d4c9731bdbe5f6b")
new ObjectId("61f4ec0a0d4c9731bdbe5f6b")
我调试并检查了它在 if 条件之后永远不会到达语句,不确定是什么问题。
【问题讨论】:
标签: node.js json mongodb object