mongodb TypeError:无法读取未定义的属性“_id”

slwdgvem  于 2022-11-03  发布在  Go
关注(0)|答案(5)|浏览(195)

我收到错误“TypeError:无法在将文档保存到名为books的集合的简单发布请求上读取undefined”“的属性”_id“,我的负载如下所示:

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

而我只是在我的路线中做db.books.save()在express中。由于我没有传递id,这在理想情况下应该可以工作,但不是在这种情况下。
下面是我在节点服务器上获得的完整错误转储:

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...
bxgwgixi

bxgwgixi1#

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.

nue99wik

nue99wik2#

请尝试以下操作:

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

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));
8tntrjer

8tntrjer3#

尽管这个问题有答案,另一个解决方案是检查node.json中的express js版本。在我自己的例子中,我将版本从3.x切换到4.x,这足以消除这个错误。我希望它能帮助一些人。

sbtkgmzw

sbtkgmzw4#

加上这两种方法对我来说很有效:

app.use(express.json()); 
app.use(express.urlencoded({ extended: true }));
t8e9dugd

t8e9dugd5#

如果express-jwt导致错误,请将res.user._id替换为res.auth._id。

相关问题