How to generate ObjectId() when manually inserting in Robo 3T?

2.4k views Asked by At

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

There are 5 answers

3
R2D2 On

Try:

 new ObjectId()

This will generate the objectId on client side

1
Pandiyan Cool On

I have tried

x=ObjectId();

and it works fine for me

enter image description here

1
Hemant Bangar On

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.

3
Wernfried Domscheit On

Do it like this:

var TestArray = []    
for (let i = 0; i < 10; i++)
   TestArray.push({ "_id": ObjectId(), "Name": "Test" }) 

{
    "Name" : "Test",
    "TestArray" : TestArray
}
0
Kate On

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.