如何使用 Mongoose 获取 ID 数组作为字符串而不是对象

How to get an array of IDs as strings instead of object with Mongoose

我正在尝试从数据库中获取所有 ID 的列表,但得到的结果不是我想要的。我希望结果是一个数组。 我希望它成为一个列表的原因是我想在另一个查询中使用它,其中条件将与这些 id 的数据一起使用,也许有一种方法可以用我得到的结果来做到这一点,但我没有也不知道该怎么做。但是如果我能把它作为一个数组来获取,我就能解决它。

这是我的做法

const ids = await Db.find({accountStatus: "active"}).distinct('_id')

结果

[
  new ObjectId("6259e7cb9604555d50939cff"),
  new ObjectId("6259f9502349309b80f215be"),
  new ObjectId("625a7619a4eb4fc6fc3e1507"),
  new ObjectId("625bb731a4eb4fc6fc3e1587"),
  new ObjectId("625bf74c13a4ee9f4ae9d61d"),
  new ObjectId("625c897f363d7af93a6fdd3b"),
  new ObjectId("625d2ef668610464781a34a3")
]

想要的结果

[
  "6259e7cb9604555d50939cff",
  "6259f9502349309b80f215be",
  "625a7619a4eb4fc6fc3e1507",
  "625bb731a4eb4fc6fc3e1587",
  "625bf74c13a4ee9f4ae9d61d",
  "625c897f363d7af93a6fdd3b",
  "625d2ef668610464781a34a3"
]

告诉我如何获得数组格式的结果。

如果你想要一个纯粹的 MongoDB 查询解决方案,你可以这样做:

Db.aggregate([{
  "$match": {
    accountStatus: "active"
  }
},
{
  $project: {
    _id: {
      $toString: "$_id"
    }
  }
}])

所有ObjectIds都转换为字符串。我保留了 distinct 运算符,因为 ID 无论如何都必须是唯一的,所以添加它没有意义。

否则,您只需映射结果并转换 ObjectId:

const ids = (await Db.find({accountStatus: "active"}).distinct('_id'))
  .map((id) => id.toString())

根据提供的示例,有多种方法可以获得您想要的结果。我将继续阐述其中的两个,一个使用回调函数,另一个使用 Promise。

方法一

const ids = await Db.find({accountStatus: "active"}).distinct('_id', 
 function(error, ids) {
    // ids is an array of all ObjectIds
    let strArr = []; // Initialize empty array
    // Iterate through ids
    for (let id of ids){
       // Push each id into strArr
       // Id is formatted as a String by using ObjectId's str attribute 
       strArr.push(id.str);
    }
    // Return resulting array
    return strArr;
});

方法二

// Storing the db call as a Promise
const dbPromise = await Db.find({accountStatus:"active"}).distinct('_id');
// Solving the Promise (can be solved later in the code)
const ids = dbPromise.then(ids => {
   // Same logic as in Method 1
   let strArr = [];
   for (let id of ids){
      strArr.push(id.str);
   }
   return strArr;
};

有用的读物​​: