I am working on a node project and can’t figure out how to use the find() function on an array of object ids.
Here is an example of a document from my mongodb database:
{
"_id": {
"$oid": "6515923586714e6ae70be0a9"
},
"managers": [
{
"$oid": "6515a0ba76e7e07f68160ef5"
},
{
"$oid": "6515a0d35c2d7cad9b070e64"
}
]
}
I tried this code.
router.get("/processes/formanager/:id",async(req,res) =>{
let processCollection = await db.collection("processes");
let query, processes, cursor;
try{query = {"$elemMatch": new ObjectId(req.params.id)};}
catch(err){res.status(404).json({error: "Not a valid id"}); return;}
try{
cursor = await processCollection.find({managers: query});
// iterate over cursor once
processes = await cursor.next();
}
catch(err){
console.log(err);
res.status(404).json({error: "No processes assigned to this manager"});
return;}
res.status(200).json({ processes })
});
I am expecting to get this document and others that meet the citeria.
If i can manage to get the first result, I will iterate over the cursor.
The result I get is null processes (when code is run as above)
OR
I get the error "$elemMatch needs an object" when I remove the "" around $elemMatch.
2
Answers
A colleague of mine gave me the correct code
cursor = await processCollection.find({managers: {$in:[new ObjectId(req.params.id)]}})
to search from an array of simple values (non array, non object) you can directly run query this query:
to search from an array of objects you should use
$elemMatch
. Here is an example: