Reputation: 4693
I am converting from mysqli
to mongodb
and having some problems with basic tasks.
This is part of a login authentication process, if the email and password matches to a record set in the dB i would like to get the _id
and create a session variable.
Heres what i have so far, all the searches i've done seems to have info on getting the _id
from different steps and i couldn't modify it for my situation.
Also, if my logic is too literal of a translation from mysqli
, please i'm open for suggestions on best practices for noSql
$collection = $db->members;
$query = array("email" => $email, "password" => $newpass);
//$cursor = $collection->findOne($query); // was told this is better but need deeper understanding
$cursor = $collection->find($query);
$result = $cursor->count();
if($result==1){
$_SESSION['email'] = $email;
//having problems here
$id = $cursor->findOne(array("_id" => $query['_id']));
$_SESSION['id'] = $id;
return true;
}else
return false;
QUESTION how do i get the _id
after authenticating a unique username and password?
Upvotes: 1
Views: 1562
Reputation: 4640
You can ensure unicity for your query (which is better for a login system) .
So use findOne()
. It will return you a document. Remember in MongoDb, you get document or a cursors of documents.
Check the documentation, you can return only a part of document. Official Documentation
$doc = $col->findOne(
array('pass'=> $pass, 'email'=>$email),//select
array('_id'=>1)//field selection
);
if ($doc){
//do your session stuff
}
Upvotes: 4
Reputation: 26739
You should not run findOne
on the cursor. The cursor points to the result from the previous query, you can use iterator_to_array to get an array with all the found records. Or you can use findOne() in the first place - it returns the actual row
$collection = $db->members;
$query = array("email" => $email, "password" => $newpass);
$result = $collection->findOne($query);
if(!empty($result)){
$_SESSION['email'] = $email;
//having problems here
$id = "" . $result['_id']; // cast to string, as its a MongoId object
$_SESSION['id'] = $id;
return true;
}else
return false;
Upvotes: 4