How to insert an array of objectId using MongoDB in Retool

Hi, I am new to Retool and I have been using MongoDB as my DB.

I want to know how can I add new ObjectIds using "insertMany" action type. Let me give you a complete background of what I wish to achieve.

I am trying to create an application for Promos & Discounts. The purpose of this application is to add / update / delete a promo. Promos itself is a separate collection that contains all the information related to promos. I am attaching an image for better understanding.

As you can see, it has multiple fields. What I am more interested in is the Courses field. So the courses field is an array of ObjectIds. Each ObjectId refers to an _id in my courses collection (attaching an image).

Screenshot 2022-05-17 at 2.05.41 PM

Now, I want to create a new promo or update the existing one. Everything is working fine but when I try using the multi-select to choose multiple courses, it is being registered as a string in my database.

I have also tried using the MongoDB extended JSON syntax but it doesn't work. If I try to put in a single ObjectId it works but for an array it doesn't work.

This is for the single ObjectId:

I would really appreciate your response. I am new to this so I am struggling with the code.

Hi @asimmehdi thanks for sharing your question here -- in case you haven't already, our docs on connecting MongoDB to Retool are here MongoDB Integration. Let me know if they help, or if I can still find out some more info for you!

Hi @alina.retool thank you for responding. I have already done everything that is in the MongoDB integration docs and all of this doesn't seems to work. I am still struggling with the string to ObjectId problem.

I see -- I'll admit that I haven't used MongoDB very much, but when looking at their own docs, it seems that you might need to adjust how to you reference the "$oid" in your courses call. How about if you checked these out? https://www.mongodb.com/docs/manual/tutorial/insert-documents/

i.e. formatting them such they could look like this?

{
    "_id": {
        "$oid": "628fcd4ec1b9e801ec0f5aef"
    },
    "courses": [
      {
        "$oid": "628fcd58c1b9e801ec0f5af0"
      },
      {
        "$oid": "628fcd79c1b9e801ec0f5af3"
      }
    ]
}

@alina.retool thank you for your response. I was able to resolve this issue. Now I can get an array of ObjectIDs with having them being converted as strings in my DB. The issue was not with the single ID, it was with the array of IDs.

But all good now. Thanks!

For people who would like to know how I fixed it, here's the code:

courses : {{selectCourses.value.map(course => { return {$oid : course} } ) }}

1 Like