Javascript foreach循环不在字符串数组上迭代
我尝试使用for-each循环检查用户的ID是否在我创建的黑名单组中。当我尝试迭代userID的字符串数组时,它说Javascript foreach循环不在字符串数组上迭代,javascript,mongoose,Javascript,Mongoose,我尝试使用for-each循环检查用户的ID是否在我创建的黑名单组中。当我尝试迭代userID的字符串数组时,它说blacklisted.forEach不是一个函数。为什么呢 query = { messageTrackingId: req.query.messageId }; messageId = true; Messages.find(query) .populate("creator", "username") .then(documents
blacklisted.forEach不是一个函数
。为什么呢
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);
});
控制台输出
documents is
5e52cca7180a7605ac94648f
ITS not a match!
BLACKLIST SERVER RESPONSE
[ '5e52e8af484eba456ca9e814',
'5e52f2cc673de71f60019c76',
'5e52f316673de71f60019c77' ]
(node:12992) UnhandledPromiseRejectionWarning: TypeError: blacklisted.forEach is not a function
我不确定如果它是一个对象,为什么它会显示为数组,但是您是否尝试过从它创建一个新数组并对其进行迭代?例如:
blacklisted = [...res[0].blacklistGroup];
blacklisted.forEach(function(entry) {
console.log(entry);
});
您的“用户”语句是否表现得像一个fetch
?如果是这样,您可能必须在使用之前将响应转换为json。类似于
User.find({ _id: otherUser }).select("blacklistGroup")
.then(res => res.json())
.then(json => {
blacklisted = json.blacklistGroup;
console.log("BLACKLIST SERVER RESPONSE");
console.log(blacklisted);
});
});
当我
console.log(res[0].blacklistGroup)
它回来了
[ '5e52e8af484eba456ca9e814',
'5e52f2cc673de71f60019c76',
'5e52f316673de71f60019c77' ]
这也是返回类型对象。为了解决这个问题,我做了以下工作:
let MyBlacklist = JSON.stringify(res[0].blacklistGroup);
MyBlacklist = JSON.parse(MyBlacklist);
然后我就可以循环通过了
let counter = 0;
for (let i = 0; i < MyBlacklist.length; i++) {
counter++;
console.log(MyBlacklist[i]);
console.log(counter);
}
你确定这是一个数组?尝试检查
Array.isArray(黑名单)
和typeof blacklisted
它显示Object。但是响应看起来像一个字符串数组。我如何转换它,以便可以对其进行迭代?我不认为我可以仅仅将它JSON.stringify,因为它将比数组更具字符串性。至少,Object比string好。数组是对象。Array.isArray
显示了什么?Array.isArray
返回FALSE,这很有趣。因此,它是一个对象(就像数组一样),并且正在使用[
分隔符记录,就像它是一个数组一样,但它不是。通过检查对象以查找哪些属性包含所需的值,可能可以找到一种解决方法(可能尝试访问[0]
,[1]
,等等),但最好修复blacklistGroup
对象的形成方式,因为它显然不是以普通数组的形式形成的。不幸的是,我不知道MongooseI添加了您的代码,但它输出了``UnhandledPromisejectionWarning:TypeError:res[0].blacklistGroup不可移植。这不是我所期望的,但这有一定的意义。您认为将数据字符串化然后查找与userId匹配的子字符串是否有效?对于某些人来说,该列表有时可能会超过100个用户,但谁知道呢。这样做会不会有性能问题?它肯定是有用的ems希望有一种更简单的方法来访问返回的数据。输出的TypeError:res.json不是一个函数
,下面的示例可以让您了解未修改的输出。请注意其中的\u id
。
5e52e8af484eba456ca9e814
1
5e52f2cc673de71f60019c76
2
5e52f316673de71f60019c77
3