I am using the MERN stack for my current project. So I am facing this problem:
Let’s say that I have the following document in MongoDB :
{
name: "Tesla Inc.",
category: "Automotive",
contact: {
state : {
name: "Texas",
city: "Austin",
address: {
streetName: "Tesla Road",
number: '1'
}
}
}
}
After I get the response from the server I want to use the address subdocument in a format like:
let address = response.contact.state.city.address
While for response.name
console logs : Tesla Inc.
if I use console.log(response.contact.state.city.address.streetName)
, I get :
Uncaught TypeError: Cannot read properties of undefined (reading 'state')
Follows my coding process
This is my Express route for quering the database :
storeRoutes.route("/enterprise").get(function (req, res) {
let db_connect = dbo.getDb("res");
const query = { name : "Tesla"};
db_connect
.collection("stores")
.findOne(query,function (err, result) {
if (err) throw err;
res.json(result);
});
});
This a Retrieve Data Function that returns the data object:
function GetEnterprise() {
const [store, setStore] = useState({
});
useEffect(() => {
async function fetchData() {
const response = await fetch(`http://localhost:5000/enterprise`);
if (!response.ok) {
const message = `An error has occurred: ${response.statusText}`;
window.alert(message);
return;
}
const record = await response.json();
if (!record) {
window.alert(`Record with id not found`);
return;
}
setStore(record);
}
fetchData();
return;
}, [1]);
return store;
}
Now lets take a look at the code in my App.js. I declare a variable called “enterprise” which is supposed to be the entire document as JavaScript object.
Note that if a property of “enterprise” object is just a key-value pair it is been retrieved fine. For example :
let enterprise = GetEnterprise();
console.log( enterprise.name );
Logs Tesla Inc
. Fine!
But if I try to retrieve an embedded document or even a property of this, I get wrong cause it has not been defined. For example :
console.log( enterprise.contact.state.adress.number );
Logs :
Uncaught TypeError: Cannot read properties of undefined (reading 'state')
. As mentioned before.
For some reason seems like I can not use the full response as a JavaScript object.
Fun fact if i implement :
let res_json = JSON.stringify(enterprise);
My console logs the whole object as expected:
{"_id":"637e4397f6723844191aa03d","name":"Tesla","category":"Automotive","contact":{"state":{"name":"Texas","city":"Austin","address":{"streetName":"Tesla Road","number":"1"}}}}
I guess it has something to do with the async and await functions. That is because if I make an irrelevant change and save my document works fine. But if I refresh the page from the browser get back to its previous state.
What am I doing wrong?
Any suggestions on retrieving a document and convert it to JS object without any “cuts” in my app?
Thanks…