TypeError: Cannot read property '_id' of u

2020-07-03 03:46发布

I am getting error "TypeError: Cannot read property '_id' of undefined" on a simple post request to save a document to the collection called books, My payload looks like this:

{
    "name": "practical view",
    "author": "DN",
    "location": "room 50"
}

And I am just doing db.books.save() in my route in express. Since I am not passing the id, this should ideally work, but not in this case.

Below is the full error dump I am getting on my node server:

C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\mongodb\lib\mongodb\mongo_client.js:411
          throw err
                ^
TypeError: Cannot read property '_id' of undefined
    at Collection.save (C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\mongodb\lib\mongodb\collection.js:393:15)
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\index.js:203:65
    at apply (C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\thunky\index.js:16:28)
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\thunky\index.js:20:25
    at Db.collection (C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\mongodb\lib\mongodb\db.js:488:44)
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\index.js:268:7  
    at apply (C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\thunky\index.js:16:28)
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\thunky\index.js:20:25
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\index.js:300:4
    at C:\NodeProjects\ExpressTutorial\Library\node_modules\mongojs\node_modules\mongodb\lib\mongodb\mongo_client.js:408:11
31 Aug 00:14:30 - [nodemon] app crashed - waiting for file changes before starting...

4条回答
男人必须洒脱
2楼-- · 2020-07-03 04:31

Please try this:

var bodyParser = require('body-parser');

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));
查看更多
Summer. ? 凉城
3楼-- · 2020-07-03 04:47

Make sure to npm install body-parser, then add

var bodyParser = require('body-parser');

app.use(bodyParser());

to the top of your code. This is also assuming you are using Express.

查看更多
等我变得足够好
4楼-- · 2020-07-03 04:49

Even though there is an answer for this question, another solution is to check the version of your express js in the node.json. In my own case, I switched the version from 3.x to 4.x and that was enough to get rid of this error. I hope it helps someone.

查看更多
一夜七次
5楼-- · 2020-07-03 04:49

This is due to the version of dependencies you are using in package.json, if you are referring any blog or tutorial go and download their code and see what version of dependencies they are using and install that dependencies in your project. Hope you solve your error, HAPPY CODING. :)

查看更多
登录 后发表回答