How can I display a populated document in react - node.js

I have a kid document in MongoDB that contains two populated documents: parent and doctor. And I want to display the parent and the doctor information in the details page of the kid.
this is the service in nodeJS:
Router.get('/kids/findKidByID',function (req, res) {
console.log(req.query)
KidModel.findOne({_id: req.params.id}).populate("doctor parent").exec(function (err,u) {
if (err) {
res.send({'state':'not ok','msg':'err:'+err})
console.log('err')
} else {
res.send(u);
console.log('succé')
}
})
});
the kid document:
[{
"firstname": "Salma",
"lastname": "Marzouk",
"doctor": {
"firstname": "Amira",
"lastname": "Messaoudi",
"email": "amira1messaoudi#gmail.com",
},
"parent": {
"firstname": "Radhia",
"lastname": "Hazgui",
}
}]
getone() {
fetch('http://localhost:4000/admin/kids/findKidByID?_id='+ localStorage.getItem("id"), { method: 'GET' } )
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({kid: data})
})
}
but I get an error: Unexpected end of JSON input

Your JSON is not well formatted:
change it to this:
[
{
"firstname":"Salma",
"lastname":"Marzouk",
"doctor":{
"firstname":"Amira",
"lastname":"Messaoudi",
"email":"amira1messaoudi#gmail.com"
},
"parent":{
"firstname":"Radhia",
"lastname":"Hazgui"
}
}
]
and you can use online sites to check your json to see if its valid, sites like this

Related

How to pluck out field value from arrays of object

I am retrieving data from mongoose database using node.js and express.
Currently, I am getting a response like this
[
{
"images": [
{
"link": "https://just-incase-from-a-far/yop.png"
},
{
"link": "https://main-link-test/lol.png"
}
]
},
{
"images": [
{
"link": "https://example-link/happy.jpg"
},
{
"link": "https://example-link/angry.jpg"
},
{
"link": "https://example-link/sad.png"
}
]
}
]
But I want a response like this
[
"https://just-incase-from-a-far/yop.png",
"https://main-link-test/lol.png",
"https://example-link/happy.jpg",
"https://example-link/angry.jpg",
"https://example-link/sad.png"
]
How can I achieve my desired response.
This is my code that gives me my response of array objects
exports.getProducts = async (req,res) => {
const result = await Product
.find({isEmpty:false})
.select("-_id -createdAt -__v -isEmpty")
.exec()
if(!result) return res.status(400).json({ data: 'No product found' });
if(result.err) return res.json({ err: err });
return res.json(result);
}
Just add a outer loop extracting the links
links = [];
result.forEach((obj) => {
links = [...obj.images.map((o) => o.link), ...links];
})

How to pull out object heading from an array

I have a JSON response structure like this
{
"_id": "620e97d76ca392a43097cca6",
"user": "620295cbd67ece90802d2522",
"orderId": "EnrL7C",
"Items": [
{
"product": {
"name": "Fresh Salad",
"id": "61f2911723ff35136c98ad3e"
},
"quantity": 1,
"price": 1250,
"_id": "620e97d76ca392a43097cca7"
},
],
}
But i want the product not to be an object, so it should look like this
{
"_id": "620e97d76ca392a43097cca6",
"user": "620295cbd67ece90802d2522",
"orderId": "EnrL7C",
"Items": [
{
"name": "Fresh Salad",
"id": "61f2911723ff35136c98ad3e",
"quantity": 1,
"price": 1250,
"_id": "620e97d76ca392a43097cca7"
},
],
}
This is my code responsible for the response output
exports.getOrder = (req,res) => {
Order.findOne({orderId: 'EnrL7C'})
.populate("Items.product", "name")
.exec((error, order) => {
if(error) return res.status(400).json({ error });
if (order) {
return res.json(order);
}else{
return res.json(['No order found']);
}
});
Sometimes when I'm too lazy to look up all the mongoose documentation and figure out what version I'm on etc, I use the .lean() to just convert it to a normal JS object, which I'm way more comfortable with.
exports.getOrder = (req, res) => {
Order.findOne({ orderId: "EnrL7C" })
.lean() // add lean
.populate("Items.product", "name")
.exec((error, order) => {
if (error) return res.status(400).json({ error });
if (order) {
// fix the structure in javascript
order.Items = order.Items.map((item) => {
const flat = {
...item.product,
...item,
};
delete flat.product;
return flat;
});
return res.json(order);
} else {
return res.json(["No order found"]);
}
});
};
Let me know if that doesn't work, so I can update the answer.

Firebase database collection returns empty array when trying to get all documents

I'm trying to get all documents from my database collection "posts" but I'm getting an empty array instead.
The strange thing is that I'm able to get all documents from another collection called "users" that has the same structure and using the exact same code.
I've spent days looking for an answer but I haven't been able to find the solution.
This is the request:
const db = admin.firestore();
exports.getAllPosts = (req, res) => {
db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let posts = [];
snapshot.forEach((doc) => {
posts.push({
id: doc.id,
body: doc.data().body,
author: doc.data().author,
createdAt: doc.data().timestamp,
voteScore: doc.data().voteScore
});
});
return res.json(posts);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And this is the response:
[]
This is what my current collection looks like:
Posts collection screenshot
This the response that I get when I return "snapshot":
{
"_query": {
"_firestore": {
"_settings": {
"projectId": "readable-bf7a6",
"firebaseVersion": "9.6.0",
"libName": "gccl",
"libVersion": "4.10.0 fire/9.6.0"
},
"_settingsFrozen": true,
"_serializer": {
"allowUndefined": false
},
"_projectId": "readable-bf7a6",
"registeredListenersCount": 0,
"bulkWritersCount": 0,
"_backoffSettings": {
"initialDelayMs": 100,
"maxDelayMs": 60000,
"backoffFactor": 1.3
},
"_clientPool": {
"concurrentOperationLimit": 100,
"maxIdleClients": 1,
"activeClients": {},
"failedClients": {},
"terminated": false,
"terminateDeferred": {
"promise": {}
}
}
},
"_queryOptions": {
"parentPath": {
"segments": []
},
"collectionId": "posts",
"converter": {},
"allDescendants": false,
"fieldFilters": [],
"fieldOrders": [
{
"field": {
"segments": [
"createdAt"
]
},
"direction": "DESCENDING"
}
],
"kindless": false
},
"_serializer": {
"allowUndefined": false
},
"_allowUndefined": false
},
"_readTime": {
"_seconds": 1622395245,
"_nanoseconds": 513743000
},
"_size": 0,
"_materializedDocs": null,
"_materializedChanges": null
}
Notice how the request for the collection "users" works successfully:
const db = admin.firestore();
exports.getAllUsers = (req, res) => {
db.collection('users')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let users = [];
snapshot.forEach((doc) => {
let users = [];
snapshot.forEach((doc) => {
users.push({
id: doc.data().userId,
email: doc.data().email,
handle: doc.data().handle
});
});
return res.json(users);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And the response:
[
{
"id": "EPoHBxhQFUXbcL3TCVx1LdUG2nO2",
"email": "ruben#gmail.com"
},
{
"id": "RqEa3dEq8TSDcZYeolXafju67rB2",
"email": "user10#gmail.com"
},
{
"id": "dxveb4n2iMQej5Q14uprsKRxFp23",
"email": "user4#gmail.com",
"handle": "user4"
},
{
"id": "YQPzBPcsqlVZk9iJEuZTHKUNuVG2",
"email": "user2#gmail.com",
"handle": "user2"
},
{
"id": "CZ05BJxi3TUOpIrmBaz539OWlbC3",
"email": "user#gmail.com",
"handle": "user"
},
{
"id": "t0t83BVwt4gVgJkDv7HL1r1MaKr1",
"email": "userJose2#gmail.com",
"handle": "Jose"
}
]
This is what the users collection looks like in Firebase:
Users collection screenshot
Why is one collection failing when the other works fine and I'm using the same code? What am I missing here?
Thanks in advance and I hope I've made it as clear as possible. Please let me know if you need me to provide anything else.
Very simple my friend, your posts documents can't be ordered like this:
.orderBy('createdAt', 'desc')
Because the post documents does not have the createdAt property, but they have a timestamp property, you should use that property to order your posts like this:
.orderBy('timestamp', 'desc')
I hope that helps 👍
I am not answering directly to #Ruben Garcia Bri, but for future firebase developers who may run into the problem of getting empty documents, I also ran into the same problem, but I solved it by adding a field to the particular document I am trying to retrieve.
Sometimes the cause is because the documents you are trying to get have no field in them.
I mean that a document must have a field before the server can recognize it as an existing document.
So if you run into this problem, consider adding a field to that document before you can successfully retrieve it.

React Native : iterate and display nested objects using Hooks

I want to display my user data stored in my api's
How can I iterate through my apis data.
Can anyone demonstrate it with example ?
My api data looks like this:
{
"data": {
"__v": 0,
"_id": "5edaa8cc76d6b20017",
"createdAt": "2020-06-05T20:19:24.365Z",
"email": "joe#gmail.com",
"name": "Joe",
"role": "user"
},
"success": true
}
Here is the example of my code:
const HomeScreen = props => {
const [dataSource, setDatasource] = useState({});
const Boiler = async () => {
const token = await AsyncStorage.getItem('token');
fetch('{{URL}}/api/v1/auth/me', {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + token,
}),
})
.then(res => res.json())
.then(responeJson => {
console.log(responeJson);
setDatasource({
...dataSource,
dataSource: responeJson,
});
})
.catch(error => {
console.error(error);
});
};
useEffect(() => {
Boiler();
}, []);
}
You response from the API is an object which you can directly render in your component without the need for iteration
Also note that when you update state, you would not explicitly set key as dataSource
Update your state like
setDatasource({
...dataSource,
...responeJson.data,
});
and then render your data like
return (
<View>
<Text>CreatedAt: {dataSource.createdAt}</Text>
<Text>email: {dataSource.email}</Text>
<Text>name: {dataSource.name}</Text>
<Text>role: {dataSource.role}</Text>
</View>
)
If you need to iterate over object use can use for..in loop.
const response = {
"data": {
"__v": 0,
"_id": "5edaa8cc76d6b20017",
"createdAt": "2020-06-05T20:19:24.365Z",
"email": "joe#gmail.com",
"name": "Joe",
"role": "user"
},
"success": true
};
function iterateOverData(data) {
for(let key in data) {
console.log(key, data[key]);
}
}
iterateOverData(response.data);

How to get comments data from instagram api

I have tried to get the Instagram media comments using API. I am getting empty array when I use API .I have tried sandbox live and also I make my profile public but still I get the comment data empty.
instagram.get('/media/2128588978223438874_685479/comments').then(data=> {
console.log(data); })
.catch(err => {
console.log(err);
})
I expected the output was : {
"data": [
{
"created_time": "1280780324",
"text": "Really amazing photo!",
"from": {
"username": "snoopdogg",
"profile_picture": "http://images.instagram.com/profiles/profile_16_75sq_1305612434.jpg",
"id": "1574083",
"full_name": "Snoop Dogg"
},
"id": "420"
},
...
] } .
but actual output I get was
{ data: [], meta: { code: 200 } }
media-id is just a placeholder for the real Id. Replace it and it will work.
Here is a request for getting media information, together with it's id.
instagram.get('/media/' + media_id + '/comments')
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
})

Resources