I'm currently tackling a node project and struggling with using the find() function on an array of object ids.
Let me share an example of a document stored in my mongodb database:
{
"_id": {
"$oid": "6515923586714e6ae70be0a9"
},
"managers": [
{
"$oid": "6515a0ba76e7e07f68160ef5"
},
{
"$oid": "6515a0d35c2d7cad9b070e64"
}
]
}
This is the code snippet I've tried:
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 })
});
My expectation is to retrieve this document along with others that meet the specified criteria. In case the first result is obtained, I will proceed to iterate over the cursor.
However, upon running the code as is, I either encounter null processes or receive the error message, "$elemMatch needs an object" when I remove the quotes around $elemMatch.