alan
alan

Reputation: 13

I can't read the _id property of a JSON object stored in MongoDB (MongoLab service)

I have a document on a mongodb on Heroku. Each object in the document has a system generated object id in the form of

"_id": {
        "$oid": "xxxxxxxxxxxxxxxxxxxxxxxx"
    }

When I make a query and get the response from the server, I stringify the response using JSON.stringify and I log the object on the server console. When I do this the following gets logged:

this is the response: [{"creator":"al","what[place]":"home","what[time [start]":"22:00","what[time][end]":"","what[details]":"","who[]":["joe","kay","mau"],"_id":"xxxxxxxxxxxxxxxxxxxxxxxx"}]

Right after the full object gets logged, I try to log the id to make sure I can access it... I want to then pass the id to a different object so that I can have a reference to the logged object.

I have this right now:

var stringyfied = JSON.stringify(res);
console.log("this is the response: " + stringyfied);
console.log("id: " + stringyfied._id);

but when the item is logged I get

id: undefined

instead of

id: "xxxxxxxxxxxxxxxxxxxxxxxx"

No matter how I try to access the _id property, I keep getting undefined even though it get printed with the console.log for the full object

I've tried:

stringyfied.id
stringyfied["_id"]
stringyfied["id"]
stringyfied._id.$oid
stringyfied.$oid

Upvotes: 1

Views: 3420

Answers (2)

NoOutlet
NoOutlet

Reputation: 1969

What is being returned is an array with one object in it.

The way to access the _id is with stringyfied[0]._id. However, it would be cleaner to pull the object out of the array instead.

There are a few ways you can do that. If this query will only ever return one result and that's all you'll want, you can use the findOne method instead. If the query may return more than a single document, then you will want to loop through the returned results.

I also agree with @dariogriffo that you'll need to use JSON.parse() on the stringified JSON variable.

Upvotes: 0

Dario Griffo
Dario Griffo

Reputation: 4274

you need to use JSON.parse(), cause JSON.stringify() is to convert to string, parse is to get the object. stringifiedid is a string

Upvotes: 1

Related Questions