[英]Javascript includes method does not work with MongoDB IDs
I was trying to use includes method to check existing MongoDB Id in an array but it is always returning false. 我试图使用include方法检查数组中现有的MongoDB Id,但它始终返回false。
Is it a some kind of bug in the includes method or am I doing something wrong below is my code 是include方法中的某种错误,还是我做错了下面的代码?
let user = req.user._id;
let keyword= req.query.q;
let userSearchHistory = await UserSearchHistory.findOne({searchKeywords: keyword}).exec();
if (!userSearchHistory.users.includes(user))
{
}
where users in my database is an array with ObjectId refering to user collection 我的数据库中的用户是一个ObjectId指向用户集合的数组
I also tried converting user object 我也尝试过转换用户对象
let user= mongoose.Types.ObjectId(req.user._id);
But still the same result. 但是结果还是一样。 Converting ObjectIds to String working for me but then I have to remove the references in my model what is the proper way to handle this ?
将ObjectIds转换为String可以为我工作,但是随后我必须删除模型中的引用,正确的处理方式是什么?
This is probably happening because userSearchHistory.users returns an array of objectIds. 这可能是由于userSearchHistory.users返回一个objectIds数组而发生的。 You can try replacing
userSearchHistory.users.includes(user)
with userSearchHistory.users.map(user=>user.toString()).includes(user)
. 您可以尝试将
userSearchHistory.users.includes(user)
替换为userSearchHistory.users.map(user=>user.toString()).includes(user)
。
This way you will be able to convert the array of objectIds to array of strings before applying 'includes' function. 这样,您将能够在应用“包含”功能之前将objectIds的数组转换为字符串的数组。
Edit : Did you try trimming spaces in 'req.user._id' by using req.user._id.trim() and then casting it to objectId? 编辑:您是否尝试过使用req.user._id.trim()修剪'req.user._id'中的空格,然后将其强制转换为objectId?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.