TypeError:无法读取未定义的属性"_id" [英] TypeError: Cannot read property '_id' of undefined

查看:344
本文介绍了TypeError:无法读取未定义的属性"_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个简单的将文档保存到名为books的集合的简单请求中收到错误"TypeError:无法读取未定义的属性'_id'", 我的有效载荷看起来像这样:

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"
}

我只是在快车路线上做db.books.save(). 由于我没有传递ID,因此理想情况下应该可以,但是在这种情况下不可以.

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

推荐答案

确保npm安装body-parser,然后添加

Make sure to npm install body-parser, then add

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

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

app.use(bodyParser());

app.use(bodyParser());

在代码顶部.这也假设您正在使用Express.

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

这篇关于TypeError:无法读取未定义的属性"_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆