How to search for documents using document _id in an aggregation pipeline in a Realm function


I want to run an aggregation pipeline on a MongoDB Realm function using object id on the match stage. I have tried using new BSON.ObjectId(jobId), new BSON.ObjectId(JSON.parse(JSON.stringify(jobId))) and each variation without the ‘new’ keyword without any success [NOTE: jobId is the string version].

Please review the code below:

 * This function fetches a job post using the document "_id" : ObjectId('xxx...')
 * Looks up alert_preferences in the settings collection that matches the job poster id, ie., userID
 * @param {String} - string of the job _id from the front end
 * @returns {Object} - document matching the document with an _id of ObjectId(jobId)

exports = async function(jobId){
  console.log('job id ', jobId, new BSON.ObjectId(jobId), `and 3 `,new BSON.ObjectId(JSON.parse(JSON.stringify(jobId))))
  const job_id = BSON.ObjectId(jobId)
  const id = new BSON.ObjectId();
  console.log('screw you job id', job_id, 'generated id ', id)

  //create pipeline that gets the job together with the alert preferences stored in the employer's settings
  const pipeline = [
      '$match': {
         _id: BSON.ObjectId(JSON.parse(jobId)) 
    }, {
        '$lookup': {
        'from': 'settings', 
        'localField': 'userID', 
        'foreignField': 'userID', 
        'as': 'settings'
        '$unwind': {
          'path': '$settings'
        '$project': {
          'settings.role': 0, 
          'settings.acquisition_channel': 0, 
          'settings.mode': 0, 
          'settings.geocode_address': 0, 
          'settings.created': 0, 
          'settings._id': 0, 
          'settings.complete': 0,
  //get a reference to the jobs collection
  const collection ="mongodb-atlas").db("kinshealth").collection("jobs")
    //get the results and first item of the object
    const results = await collection.aggregate(pipeline)
    console.log('collection ', JSON.stringify(results))
    console.log(`error fetching id  : -> ${err}`)

Thanks for your help!

Hi @Excel_Health_Careers_Training ,

First what is the permission on this function ? Is it application level or system level?

Does the user running this pipeline has permission on the matched id?

Now regarding syntax it doesn’t need all extra parsing just passing a string to BSON helper, it should be:

      '$match': {
         _id: BSON.ObjectId(jobId) 
const results = await collection.aggregate(pipeline).toArray()

Try to add to array in the end of aggregation execution.

See more examples :