最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Cannot create property '_id' on string - Stack Overflow

programmeradmin1浏览0评论

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 = '';
    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?

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?

Share Improve this question edited Jun 14, 2018 at 19:01 Adam Azad 11.3k5 gold badges30 silver badges72 bronze badges asked Jun 14, 2018 at 18:56 Hot ZellahHot Zellah 1,0813 gold badges13 silver badges23 bronze badges 4
  • 1 body is not an object as apparent from the error. – Adam Azad Commented Jun 14, 2018 at 19:02
  • Did you add the request module in npm ? – Alex Commented Jun 14, 2018 at 19:05
  • @AdamAzad so what do I need to change am new to this stuf though? – Hot Zellah Commented Jun 14, 2018 at 19:06
  • @Alex Yes , other endpoints works – Hot Zellah Commented Jun 14, 2018 at 19:07
Add a comment  | 

3 Answers 3

Reset to default 11

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]);
            }
        });
    });
});

Base on your previous question, I see your body var is currently a string, so you need to change it.

app.post('/data', (req, res) => {
let url = 'https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190';
request(url, function (error, response, body) {
    var insertObj = JSON.parse(body)
    db.collection('data').insert(insertObj, (err, result) => {
        if (err) {
            res.send({
                'error': 'An error has occured'
            });
        } else {
                res.send(result.ops[0]);
        }
    });
});
});

As you can see, " _id can't be string "

when you request to url "https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190"

it will return string that look like JSON

'{"id":401478,"page":1,"results":[{"author":"Gimly","content":"There is some decent fun to be found in _Beyond Anarchy_. It's more _Escape from LA_ than it is _Death Race 2000_, but still an entry in the franchise, which brings me to the core problem of Beyond Anarchy: Is it even really a _Death Race_ movie? The answer is yes, but to go beyond that an ask: Should it have been a _Death Race_ movie? The answer's probably no.\r\n\r\nAs I said to begin with, I had some fun with the movie, but the things that kept bringing it down were its awkward, half-hearted attatchments to the movies in the series that had gone before it. If they had have abandoned those sentiments completely, it probably would have made a better viewing experience, but then, if that had been the case, how could you call it _Death Race 4_? The opposite approach probably would have worked too, having Beyond Anarchy be an actual sequel that follows _Death Race 3_ and what came before in a way that makes sense, but then, it couldn't have been even close to the movie that we got.\r\n\r\nInstead we have _Beyond Anarchy's_ sequel-limbo status, a movie that I don't regret watching, but that also can't really work for people who are fans of the _Death Race_ franchise, or for people who have never even seen a Death Race movie.\r\n\r\n_Final rating:★★½ - Had a lot that appealed to me, didn’t quite work as a whole._","id":"5af426b50e0a2639430091df","url":"https://www.themoviedb.org/review/5af426b50e0a2639430091df"}],"total_pages":1,"total_results":1}'

so you must do the JSON.parse to make the body change from string to object (inserting data to mongo must be object)

let url = 'https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190';
request(url, function (error, response, body) {
    body = JSON.parse(body);
    db.collection('data').insert(body, (err, result) => {
        //
    });
});
发布评论

评论列表(0)

  1. 暂无评论