node.js - How to get data from mongodb using _id.$oid object? -


i trying find objects logged-in user id.

function getitems(req, res) {     var userid = json.stringify(req.user._id);      items.find({user_id: userid}, function(err, items) {         if (err) {             res.send(err)         }         else {             res.json(items);         }     });  }  // logged-in user app.get('/useritems', isloggedin, function(req, res) {     getitems(req, res); }); 

user json data looks like:

"_id": {      $oid": "55c772bce97e9a500b3754ae" } 

item object such:

{     "_id": {         "$oid": "55d086a182377f840844ee78"     },     "user_id": "55c772bce97e9a500b3754ae",     itemspecs:[         //...     ] } 

it returns empty array because userid doesn't match user_id guess. try set:

var userid = '55c772bce97e9a500b3754ae'; 

it returns items userid.

var userid = json.stringify(req.user._id); console.log(typeof userid); // >> string 

so, userid user object , user_id items object same type: string.

probably stupid can't see reason why user _id object doesn't match user_id in items object.

how items have logged-in user id using logged-in user id _id.$oid object?

when call json.stringify(req.user._id);, string json representation of objectid object. should along line of "{ "$oid": "55c772bce97e9a500b3754ae" }" not same string "55c772bce97e9a500b3754ae".

to hexadecimal representation of objectid, use req.user._id.tohexstring().

by way, manual references between documents, using actual objectid's more efficient using hex strings. raw objectid 12 byte while 24 character hex string 28 byte.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -