Mongodb Object Id not being inserted as an objectId in laravel #2641
Replies: 1 comment
-
|
Hey — I feel your pain. This usually happens because Laravel is inserting exactly what you pass in (a PHP string), and MongoDB won’t “auto-cast” it to an ObjectId for you. To store an actual ObjectId, you must pass a Ex(Insert & Update) use MongoDB\BSON\ObjectId;
Model::create([
'product_cache_id' => new ObjectId($idString),
]);
// or update
$m->product_cache_id = new ObjectId($idString);
$m->save();if you want to querying by Model::where('_id', new ObjectId($idString))->first();If ObjectId casting isn’t available in your version, a custom setter/mutator that wraps new ObjectId($value) works the same. Also, note that MongoDB will only auto-generate an ObjectId for the document _id field when you don’t supply one — it won’t automatically convert other fields from string to ObjectId. Hope this helps !! 🙌 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
i have looked everywhere and can't seem to find how to insert mongodb objectId into the db without them being inserted as strings while working with database, i can't create a new one either, it inserts as strings and this has really imocted my work, as i've been stuck on it for over a week now, all methods i try seem to only insert it as a string or do not at all, i need to insert this objectId because the former developer had setup the db to use objectId references which i then use to make lookup aggregration requests, they've done a lot of inserts and i cannot redesign the db to fit with the constraints of php/laravel, as the former project was done with node express...how do i go about this, i am really fed up at this time...
Beta Was this translation helpful? Give feedback.
All reactions