Folks,
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,
'settings.userID':0
}
}
]
//get a reference to the jobs collection
const collection = context.services.get("mongodb-atlas").db("kinshealth").collection("jobs")
try{
//get the results and first item of the object
const results = await collection.aggregate(pipeline)
console.log('collection ', JSON.stringify(results))
}catch(err){
console.log(`error fetching id : -> ${err}`)
}
};
Thanks for your help!