kanu mahajan
kanu mahajan

Reputation: 109

auto generate _id (mongodb) for subdocuments in mongodb with Laravel

I want to create the objectId (_id) for subdocuments automatic. I know how to generate the MongoDB objectId when data is entered in collection. But is there any way it should save automatic and generate without writting code?

$product = new Product;
$product->product_name = "Gym Bag";
$skus = array(
        array(
            '_id'  =>  new \MongoDB\BSON\ObjectID(); // this will generate here
            'sku' =>"100",
            'price' => 1500,
            'stock' =>10
        ),
        array(
            // here it will not generate as i have not defined.
            'sku' =>"101", 
            'price' => 1600,
            'stock' =>5
        )
    );
 $product->skus = $skus;
 $product->save();

So, once skus sub document is created it will automatically generate the _id in subdocument. Is there any settings need to do at Prodcut Model or globally?

Upvotes: 2

Views: 231

Answers (1)

Joe
Joe

Reputation: 28316

MongoDB will automatically create an _id for each document inserted into a collection.

It does not automatically create any values for embedded documents or arrays.

If you need an ObjectId in a document in an array inside of the top-level document, you will need to explicitly create one.

Upvotes: 0

Related Questions