[英]foreach loop not iterating over string array
I'm trying to use a for each loop to check if a user's ID is in a blacklist group I created.我正在尝试使用 for each 循环来检查用户的 ID 是否在我创建的黑名单组中。 When I try to iterate over the string array of userID's, it says
blacklisted.forEach is not a function
.当我尝试遍历 userID 的字符串数组时,它说
blacklisted.forEach is not a function
。 Why is that?这是为什么?
query = { messageTrackingId: req.query.messageId };
messageId = true;
Messages.find(query)
.populate("creator", "username")
.then(documents => {
console.log("documents is");
console.log(documents[0].creatorId);
let otherUser;
if (documents[0].creatorId === req.query.creatorId) {
console.log("ITS A MATCH!")
otherUser = documents[0].recipientId;
}
else if (documents[0].recipientId === req.query.creatorId) {
console.log("ITS not a match!")
otherUser = documents[0].creatorId;
}
let blacklisted = false;
User.find({ _id: otherUser }).select("blacklistGroup").then((res) => {
blacklisted = res[0].blacklistGroup;
console.log("BLACKLIST SERVER RESPONSE");
console.log(blacklisted);
blacklisted.forEach(function(entry) {
console.log(entry);
});
CONSOLE OUTPUT控制台输出
documents is
5e52cca7180a7605ac94648f
ITS not a match!
BLACKLIST SERVER RESPONSE
[ '5e52e8af484eba456ca9e814',
'5e52f2cc673de71f60019c76',
'5e52f316673de71f60019c77' ]
(node:12992) UnhandledPromiseRejectionWarning: TypeError: blacklisted.forEach is not a function
I'm not sure why it would display as an array if it's an object, but have you tried creating a new array from it and iterating over that?如果它是一个对象,我不确定为什么它会显示为一个数组,但是您是否尝试过从中创建一个新数组并对其进行迭代? For example:
例如:
blacklisted = [...res[0].blacklistGroup];
blacklisted.forEach(function(entry) {
console.log(entry);
});
Is you "User" statement acting like a fetch
?您的“用户”语句是否像
fetch
? If so, you may have to convert your response to json before using it.如果是这样,您可能必须在使用之前将响应转换为 json。 Something like...
就像是...
User.find({ _id: otherUser }).select("blacklistGroup")
.then(res => res.json())
.then(json => {
blacklisted = json.blacklistGroup;
console.log("BLACKLIST SERVER RESPONSE");
console.log(blacklisted);
});
});
I realized that for some reason when I console.log(res[0].blacklistGroup)
it was returning我意识到由于某种原因,当我
console.log(res[0].blacklistGroup)
它正在返回
[ '5e52e8af484eba456ca9e814',
'5e52f2cc673de71f60019c76',
'5e52f316673de71f60019c77' ]
which is also return type Object.这也是返回类型对象。 So to solve this, I did the following:
所以为了解决这个问题,我做了以下事情:
let MyBlacklist = JSON.stringify(res[0].blacklistGroup);
MyBlacklist = JSON.parse(MyBlacklist);
then I was able to loop through然后我就可以循环了
let counter = 0;
for (let i = 0; i < MyBlacklist.length; i++) {
counter++;
console.log(MyBlacklist[i]);
console.log(counter);
}
OUTPUT:输出:
5e52e8af484eba456ca9e814
1
5e52f2cc673de71f60019c76
2
5e52f316673de71f60019c77
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.