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.
Thanks!