mongodbmongodb-stitch

How can I generate a Mongo ObjectId in a Mongo Stitch Function?


I am trying to generate a Mongo ObjectID in a stitch function before object insertion, and keep getting errors. I've tried const _id = ObjectId(); and also const _id = mongoService.ObjectId() and keep getting errors. Is it possible to generate a Mongo ObjectId in a stitch function before inserting an item in collection?


Solution

  • Is it possible to generate a Mongo ObjectId in a stitch function before inserting an item in collection?

    Yes, to generate a new ObjectId you can use the BSON utility package:

    let id = new BSON.ObjectId(); 
    

    You can also turn string hex to ObjectId using similar call, i.e:

    let id = new BSON.ObjectId("5e5dd3547e96ac1963d1b841"); 
    

    See also Stitch: Utility Packages for a list of utility packages provided.