I am creating simple rest API I have an endpoint for post/data to save data to the MongoDB from external API,
Here is what I have so far:
app.post('/data', (req, res) => {
let url = 'https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190';
request(url, function (error, response, body) {
db.collection('data').insert(body, (err, result) => {
if (err) {
res.send({
'error': 'An error has occured'
});
} else {
res.send(result.ops[0]);
}
});
});
});
when i test api in postman localhost:8000/data
in console I get error:
TypeError: Cannot create property '_id' on string
What am I doing wrong here?
body
is the JSON string, to convert it to JSON object, use JSON.parse(body)
app.post('/data', (req, res) => {
let url = 'https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190';
request(url, function (error, response, body) {
// convert to JSON
var bodyJson = JSON.parse(body)
db.collection('data').insert(bodyJson, (err, result) => {
if (err) {
res.send({
'error': 'An error has occured'
});
} else {
res.send(result.ops[0]);
}
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With