skip to Main Content

I’m trying to generate ObjectId() when inserting manually in Robo 3T.

Code below seems doesn’t work. I wanted every object inside TestArray have a unique id.

How do I generate ObjectId manually?

{
    "Name" : "Test",
    "TestArray" : [ 
        {
            "_id" : ObjectId(),
            "Name" : "Test"
        }
    ]
}

5

Answers


  1. Try:

     new ObjectId()
    

    This will generate the objectId on client side

    Login or Signup to reply.
  2. I have tried

    x=ObjectId();
    

    and it works fine for me

    enter image description here

    Login or Signup to reply.
  3. You don’t have to generate the _id, just don’t that field in your insert query and mongo will automatically generate it for you.

    Login or Signup to reply.
  4. Do it like this:

    var TestArray = []    
    for (let i = 0; i < 10; i++)
       TestArray.push({ "_id": ObjectId(), "Name": "Test" }) 
    
    {
        "Name" : "Test",
        "TestArray" : TestArray
    }
    
    Login or Signup to reply.
  5. While this is pretty tedious, if you want to use the typical Meteor structure of a 17 character alphanumeric string, you can use a random text generator online to generate a string, then do a .find() in the collection to see if it exists, and then pass it in your .insert() as the _id value in your insert object. I had the same problem and this was the way I got around it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search