Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot create property '_id' on string

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?

like image 431
Hot Zellah Avatar asked Jun 14 '18 18:06

Hot Zellah


Video Answer


1 Answers

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]);
            }
        });
    });
});
like image 101
Adam Azad Avatar answered Sep 21 '22 15:09

Adam Azad