0

I'm trying to get the ID from mongodb to modify and delete user from a simple CRUD app with PHP and vue.js using axios

When I insert any user, I get this id.

{ "$oid": "5a8fd1ef1233610e40007667" }

I just need the ID that mongodb generate itself.

"5a8fd1ef1233610e40007667"

I'm using POST to get the ID and this is what I get when I use var_dump()

string(15) "[object Object]"

¿Any idea of how to get that ID? I've already tried several things, I hope you guys can help me

A. Morales
  • 123
  • 2
  • 19
  • Possible duplicate of [How do you get the string value of a MongoID using PHP?](https://stackoverflow.com/questions/7861332/how-do-you-get-the-string-value-of-a-mongoid-using-php) – Peon Feb 27 '18 at 09:11

1 Answers1

2

See the The MongoDB\BSON\ObjectId class.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the driver automatically generates an ObjectId for the _id field.

specifically MongoDB\BSON\ObjectId::__toString, which returns the hexidecimal representation of the ObjectId. You can invoke __toString by casting the ObjectId to string, for example:

$stringID = (string)$objectID;

You do not need to create the ObjectID when you insert the record, for example (based on your comment)

$bulk = new MongoDB\Driver\BulkWrite();
$doc  = [ 'firstname' => $firstname, 'lastname' => $lastname ];
$bulk->insert($doc);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result);

The mongo driver will create and set the '_id' field, insert takes the array by reference and can alter it.

Geoffrey
  • 10,843
  • 3
  • 33
  • 46
  • I insert the id in database using BulkWrite. $bulk = new MongoDB\Driver\BulkWrite; $doc = [ '_id' => new MongoDB\BSON\ObjectID, 'firstname' => $firstname, 'lastname' => $lastname ]; $bulk->insert($doc); This generate a random number of 24 letters and digits. – A. Morales Feb 27 '18 at 09:24
  • 1
    Please see the updated answer showing how to perform this correctly. – Geoffrey Feb 27 '18 at 09:31
  • You're right, I don't need to create the ObjectID. I did it and in echo I get string(0) "" . – A. Morales Feb 27 '18 at 09:56
  • 1
    Please read up on `BulkWrite`, ensure you are calling `executeBulkWrite`, and check it's return value. It seems like `BulkWrite` is not what you are looking for. – Geoffrey Feb 27 '18 at 10:38
  • 1
    However, this doesn't answer my question. Your talking about insert, and my question is about delete and update. I still get the `[object Object]`. I've tried it to handle it without vue.js and works perfectly. I guess, the "problem" is when vue.js and mongodb works togheter. Either way, I thank you for your replys. – A. Morales Mar 01 '18 at 11:23