I am trying to get a list of all ids from a database but I am getting a result that I don’t want. I want the result to be an array.
There reason why I want it to be a list is that I want to use it in another query where the condition will work with the data of those ids, maybe there is a way to do that with the result I am getting but I don’t know how to do it as well. But if I can get it as an array, I will be able to solve it.
Here is how I am doing it
const ids = await Db.find({accountStatus: "active"}).distinct('_id')
result
[
new ObjectId("6259e7cb9604555d50939cff"),
new ObjectId("6259f9502349309b80f215be"),
new ObjectId("625a7619a4eb4fc6fc3e1507"),
new ObjectId("625bb731a4eb4fc6fc3e1587"),
new ObjectId("625bf74c13a4ee9f4ae9d61d"),
new ObjectId("625c897f363d7af93a6fdd3b"),
new ObjectId("625d2ef668610464781a34a3")
]
desired result
[
"6259e7cb9604555d50939cff",
"6259f9502349309b80f215be",
"625a7619a4eb4fc6fc3e1507",
"625bb731a4eb4fc6fc3e1587",
"625bf74c13a4ee9f4ae9d61d",
"625c897f363d7af93a6fdd3b",
"625d2ef668610464781a34a3"
]
Let me know how I can get the result in an array format.
2
Answers
If you want to have a pure MongoDB query solution you can do it like this:
All
ObjectIds
are converted to strings. I kept out thedistinct
operator since Ids must be unique anyways so there is no point in adding this.Otherwise you can just map over your result and transform the ObjectIds:
Based on the example provided, there are multiple ways of getting to your desired result. I will proceed to enunciate two of them, one using a callback function and the other one using a Promise.
Method 1
Method 2
Useful readings: