0

I am writing Mongodb Stitch, functions.

The weird part is, writing it within Mongodb Stitch function client, it has to do BSON.ObjectId

    const games = mongodb.collection("games");
    const gameId = "5cb9404ffc6da85909eb561c";
    const objectId = BSON.ObjectId(gameId);
    const query = { "_id" : objectId };
    return games.findOne(query);

But, when I use my app to pass the arg to the function, it will complain [StitchServiceError: Error: ObjectId in must be a single string of 12 bytes or a string of 24 hex characters]

Which I have to revert it back to

    const gameId = "5cb9404ffc6da85909eb561c";
    const query = { "_id" : gameId };
    return games.findOne(query);

Which this will return null if I test it within MongoDB Stitch function client.

Why MongoDB designs in this way?

Yumiko
  • 448
  • 5
  • 16

2 Answers2

0

For app to work, you only need to pass the id string.

const gameId = "5cb9404ffc6da85909eb561c";
const query = { "_id" : gameId };
return games.findOne(query);
Yumiko
  • 448
  • 5
  • 16
0

This worked for me:

    exports = function(payload, response) {
      const mongodb = context.services.get("mongodb-atlas");
      const collection = mongodb.db("mydatabase").collection("mycollection");
      // const id = "5f2b7706fae92314e01a2c3c";
      // let cursor = collection.findOne({_id: BSON.ObjectId(id)});
      let cursor = collection.findOne({_id: BSON.ObjectId(payload.query.id)});
      cursor.then(function(result){
        response.setStatusCode(200);
        response.setHeader(
          "Content-Type",
          "application/json"
        );
        response.setBody(JSON.stringify(result));
      });
    };

Then to test:

https://yourwebhookurl?id=5f2b7706fae92314e01a2c3c

Also see: https://intercom.help/mongodb-atlas/en/articles/1566512-how-do-i-work-with-objectid-in-stitch

Mr. J
  • 307
  • 2
  • 9