TypeError: Unable to read property "_id" from undefined

I get the error "TypeError: I can not read the property" _id "from undefined" on a simple mail request to save the document in a collection called books . My payload is as follows:

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

And I just do db.books.save() in my route in express. Since I do not pass id, this should work perfectly, but not in this case.

Below is the full error dump that I get on the 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... 
+6
source share
3 answers

Make sure npm installs body-parser, then add

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

app.use (bodyParser ());

to the top of your code. It also assumes that you are using Express.

+8
source

Please try the following:

 var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); 
+4
source

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

0
source

Source: https://habr.com/ru/post/952856/


All Articles