Get $oid from array of results

Hi folks! I am attempting to use MongoDB directly from an electron/ReactJS app and I am struggling with one thing: Getting the object id from the returned results.

My code in the main.tsx file:

const client = new MongoClient(url, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
client.connect();
const db = client.db('Blind');

ipcMain.handle(
  'get-data',
  (event: Event, arg: string, type: string, query: string) => {
    const coll = db.collection(arg);
    if (type === 'projection') {
     const projection = query;
      const f: Promise = coll.find({}, projection); // .populate('all');
     return f.toArray();
    }
    if (type === 'find') {
      const f: Promise = db.collection(arg).find(query);
      return f.toArray();
    }
    return null;
  }
);

This works as hoped, and in my render code, I do the following:

useEffect(() => {
    const q = JSON.parse('{ "Name": 1, "_id": 1 }');
    window.electronAPI
      .getData('Attendees', 'projection', q)
      .then((response) => {
        console.log('UseEffect: ', response[0]);
        setAttendees(response);
      })
      .catch((error: Error) => {
        console.log('Error: ', error);
      });
  }, []);

This, too, works as expected. But what I’m trying to do, and cannot figure out how to do, is extract the oid from the returned result.

{
    "_id": {},
    "Name": "First Last",
    "Address": "6012 Main Street",
    "City": "MyCity",
    "State": "NC",
    "Zip": "27540",
    "HomePhone": "919-555-1212",
    "CellPhone": " ",
    "Email": " ",
    "Location": {
        "lat": 35.77,
        "lng": -78.44
    },
    "Notes": ""
}

The _id seems impossible to access. I know I’m looking for _id.$oid but that seems to not exist. Do I need to parse the return from the query different way than using the simple toArray() function? And if so, how?

Sorry if this is a simple question, but I’m a simple person. :slight_smile:

Thanks!

Since no one answered … I’ll answer myself :slight_smile:

Doing MongoDB queries from electron is a bit of an odd thing and the asynchronous stuff makes it harder (for me anyway) to figure out what’s going on, etc.

Anyway, when I was returning the results in an array, using cursor.toArray() it was impossible to later extract the _id from the results.

However, I discovered that if I iterate on the cursor before turning it into an array, I have access to it.

So the function in the main.tsx file needs to be:

ipcMain.handle(
  'get-data',
  async (event: Event, arg: string, type: string, query: string) => {
    const res = [];
    if (type === 'projection') {
      const projection = query;
      const f = db.collection(arg).find().project(projection);
      await f.forEach((doc) => {
        res.push(JSON.stringify(doc));
      });
      return res;
    }
    if (type === 'find') {
      const f = db.collection(arg).find(query);
      await f.forEach((doc) => {
        res.push(JSON.stringify(doc));
      });
      return res;
    }
  }
);

At which point the returned array in the renderer end now has access to the _id field as needed.

Just in case anyone wanted to know.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.