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'
}
}
}
}
What I get as response after using findOne({ name : "Tesla"})
is :
{_id: '637e4397f6723844191aa03d', name: 'Tesla', category:
'Automotive', contact: {…}}
As you can see contact object is undefined
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);
});
});
Result: After typing browser url http://localhost:5000/enterprise
returns the expected value:
{"_id":"637e4397f6723844191aa03d","name":"Tesla","category":"Automotive","contact":{"state":{"name":"Texas","city":"Austin","address":{"streetName":"Tesla Road","number":"1"}}}}
- This a Retriever 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 ${id} not found`);
window.alert(`Record with id not found`);
return;
}
setStore(record);
}
fetchData();
return;
}, [1]);
//debugging
console.log('tesla: ' + store);
window.store = store;
let res_json = JSON.stringify(store);
console.log('res_json :' + res_json);
return store;
}
Result:
Before GetEnterprise() function returns store
I have added these 4 lines of code for debugging:
console.log('tesla: ' + store);
window.store = store;
let res_json = JSON.stringify(store);
console.log('res_json :' + res_json);
1st line logs [object Object]
which is not that informative for what I am getting back as a response.
So I came up with 2nd line which enables to debug directly from the browser console.
After I type store my console logs:
{_id: '637e4397f6723844191aa03d', name: 'Tesla', category: 'Automotive', contact: {…}}
So my contact
object is missing(undefined
).
Now fun fact is the 3rd and 4rd lines :
let res_json = JSON.stringify(store);
console.log('res_json :' + res_json);
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"}}}}
Which is really weird.
I guess it has something to do with the async and await functions. But I am not sure.
What am I doing wrong?
Any suggestions …?