从对象ID数组中删除用户ID

时间:2019-09-06 20:57:49

标签: node.js mongodb mongoose

我在一个数组中有四个对象ID。我也有一个用户ID。我想从对象ID数组

中删除用户ID
allowners= [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b, 
5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d]
user._id = 5d6caefdbb6f2921f45caf1d

我尝试了什么

  const userid = user._id
  const vendors = allowners.filter((item) => userid !== item)

我得到的结果是

  vendors = [ 5d6caefdbb6f2921f45caf1d,
     5d6caee9bb6f2921f45caf1b,
     5d6dfcd6e3b11807944348b8,
     5d6caefdbb6f2921f45caf1d ]

我期望的结果是

    vendors = [ 5d6caee9bb6f2921f45caf1b,5d6dfcd6e3b11807944348b8]

2 个答案:

答案 0 :(得分:0)

如果allowners数组中的这些ID是Mongoose ObjectID,则需要在ObjectID对象上使用 .equals 方法进行比较:

user._id = "5d6caefdbb6f2921f45caf1d"; //even if this is an ObjectID of mongoose
const userid = user._id;
const vendors = allowners.filter(item => !item.equals(userid));

另一种方式:在ObjectID上使用 toString() (仅与字符串-用户ID相比有效)

vendors = allowners.filter(item => item.toString() !== userid);

输出:

console.info("Filtered IDs::", vendors);
Filtered IDs:: [ 5d6caee9bb6f2921f45caf1b, 5d6dfcd6e3b11807944348b8 ]

答案 1 :(得分:0)

如果您的数据类型正确匹配,您的结果应计算为预期结果。例如:

// Your array of IDs of type {String}
const allowners = ['5d6caefdbb6f2921f45caf1d', '5d6caee9bb6f2921f45caf1b', '5d6dfcd6e3b11807944348b8', '5d6caefdbb6f2921f45caf1d'];

// Your user object with an id of type {String}
const userObject = {
    id: '5d6caefdbb6f2921f45caf1d'
}

// Extract the id from your user object, and store in a userId variable If you wish :-)
const userId = userObject.id;

// Using your code with just changes in the variable name (userid -> userId)
const vendors = allowners.filter((item) => userId !== item);

// The result
console.log(vendors); // [ '5d6caee9bb6f2921f45caf1b', '5d6dfcd6e3b11807944348b8' ]