简体   繁体   中英

Convert objectID or _id from MongoDB Stitch query to string and map it

I am able to query a MongoDB Stitch database, but I get different results.

If I console log all my data, it appears like this (note the 'id: Uint8Array(12) [ 94, 67, 83, … ]'

item.find().asArray()
.then(data => {
    console.log("Found docs", data)
  });

However if I query it as an array:

      // Find database documents
      item.find({})
      .toArray()
      .then(xyz => 
        this.setState({xyz})
      )

Here is the data I receive, and state:

{
    "xyz": [
      {
        "_id": {
          "id": "DataView(12)",
          "get_inc": "",
          "getInc": "",
          "generate": "",
          "generationTime": 1581470496,
          "inspect": "toString"
        },
        "company": "AAA",
        "url": "http://www.google.com",
        "loc": "sac, ca",
        "gender": "female",
        "tags": "clothes"
      },
      "{_id: {…}, company: \"BBB\", gender: \"male\", loc: \"sf…}",
      "{_id: {…}, company: \"ZZZ\", gender: \"male\", loc: \"oa…}"
    ]
  }

I would like to grab the objectID (which should be something like "5e435320e45ce24954381c52") which appears to be a unique key of a "bsonType": "objectId" schema, and I assume I need it converted as a string (?), so I can map it and have it serve as a unique key for use later in a table ("Each child in a list should have a unique "key" prop.").

Thanks!

Already is an ObjectId .

To get the string value just use toString()

item.find().toArray()
.then(data => {
    console.log(data.map(elem => elem._id.toString()));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM