How to pull out an object id in mongodb and search against it?

Please note: "user_id" in my collection is plansNOT an object_id. I store it in the collection plansfor reference to the user _id in the collection user_accounts. I was thinking of storing usernames in all collections to refer to the user, but that would not be an idea if the user wants to change his username.

// Retrieve User ID
$query = array("username" => $user_id);
$fields = array("_id");
$user = $collection_user->findOne($query, $fields);

// Retrieve plans made by user
$query = array("user_id" => $user['_id']);
$fields = array("plan_title");
$data = $collection_plans->find($query, $fields);

If I hardcode _id in the query, it works fine as follows:

// Retrieve plans made by user
$query = array("user_id" => "4cc1790f6c0d49bf9424fc73");
$fields = array("plan_title");
$data = $collection_plans->find($query, $fields);
+3
source share
1 answer

It looks like I had to convert it to a string.

$uid = $user['_id'] . "";
+4
source

Source: https://habr.com/ru/post/1771013/


All Articles