2
{
  acknowledged: true,
  insertedId: new ObjectId("612d9d08db9c20f031033478")
}

This was the JSON format I got while I added a file and some other things to MongoDB and I want to get this id separately to save the file to another folder.

Can anyone please explain this?

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
001 falah
  • 21
  • 1

3 Answers3

2

I believe this question was answered by Vikas in this thread How to get value from specific key in NodeJS JSON [duplicate]

Edited The Answer. Now Its working for above object in question

You can use following function to access the keys of JSON. I have returned 'mm' key specifically.

function jsonParser(stringValue) {
 
        var string = JSON.stringify(stringValue);
        var objectValue = JSON.parse(string);
        return objectValue['mm'];
}
0

if this is a JSON String, at first of all you have to parse it to object liertal, then you can access the specified property you mentioned, so you can do like the following:

function parseJsonString(jsonString) {
    // first parse it to object
    var obj = JSON.parse(jsonString);
    // now access your object property/key
    var id = obj.insertedId;

}

0

If your doing it on mongodb shell or Robo3T then, the line of code would be: db.collection_name.find({},{insertedId:1}) This is related to projection. 1 represents you want to display it as your output.

In your case as you want only the value of your object id to get displayed, you have to use .valueOf() ; that is ObjectId().valueOf().

                     ->  insertedId: new ObjectId("612d9d08db9c20f031033478") 
                     ->  ObjectId("612d9d08db9c20f031033478").valueOf()
                     ->
                     ->  612d9d08db9c20f031033478

Your can refer this : https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/ site for your reference.

So you can use this .valueOf() in your code and get the id saved in the document