javascriptmongodbmongodb-querymongodb-stitch

Using MongoDB Stitch webhook service function, how can I convert the returned "insertedId" to string?


I'm creating MongoDB Stitch http services (using the 3rd Party Services > Incoming Webhooks > Function Editor) for a simple CRUD application and I am trying to insertOne() document and then return the document id as a string.

The insertion works as expected and I await the result and store it in a variable.

const result = await collection.insertOne(payload.query)
const id = result.insertedId

The problem is trying to convert this id to string. I'm guessing it's due to my lack of understanding the MongoDB Extended JSON and BSON types, etc. I've read all parts of the documentation that I thought could provide a solution here.

I've tried the following to convert the return value to a string:

id.toString() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id.valueOf() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id['$oid'] // undefined
Object.values(id.insertedId) // throws error: {"message":"'values' is not a function"}
id.str // undefined
result.str // undefined

Not sure what else to try and would really appreciate if someone can point me in the right direction here to provide a solution.

Thank you in advance.


Solution

  • Found a solution after noticing this section of the documentation: MONGODB STITCH > Functions > Reference > JSON & BSON

    const result = await collection.insertOne(payload.query)
    const id = JSON.stringify(
      JSON.parse(
        EJSON.stringify(result.insertedId)
      ).$oid
    ).replace(/\W/g,'');
    

    Seems a bit hacky just for getting the id of the document into a string, but it will work for now.