mongodb - TypeError:无法在 insertOne 的 insertDocuments 中读取未定义的属性“_id”
问题描述
引发此错误时,我试图将记录插入集合中。我浏览了insertOne上的 mongodb 文档,我知道当 _id 没有像我的情况那样指定时,mongod 会自动添加,所以我想知道为什么会出现未定义的 id 错误。
这是我正在使用的代码,首先是 api 路由和我要插入的数据
app.post('/api/contacts', (req, res) => {
// retrieve the user being added in the body of the request
const user = req.body;
// obtain a reference to the contacts collection
const contactsCollection = database.collection('contacts');
// insert data into the collection
contactsCollection.insertOne(user, (err, r) => {
if (err) {
return res.status(500).json({error: 'Error inserting new record.'});
}
const newRecord = r.ops[0];
return res.status(201).json(newRecord);
});
});
插入的json数据
{
"name": "Wes Harris",
"address": "289 Porter Crossing, Silver Spring, MD 20918",
"phone": "(862) 149-8084",
"photoUrl": "/profiles/wes-harris.jpg"
}
与托管在 mlab 上的数据库的数据库连接成功且没有错误。这里可能有什么问题,我该如何解决这个错误?
解决方案
错误消息意味着您传递给 insertOne 的对象是未定义的(因此它无法读取它的 _id 属性)。您可能想看看 req.body 究竟包含什么,因为那是作为用户传递的内容。(我不知道 TypeScript,但是在 node/express 中,当我没有正确设置 bodyParser 时,我遇到了这样的错误)
推荐阅读
- python - 如何避免使用 Shell=True
- ios - 在 UIWindow 的子视图中添加时,UIButton 不响应点击
- javascript - 如何从 javascript/ajax 绑定 ASP.net 数据表
- android - 来自imageview的图像在共享时仅显示黑色图像?
- mysql - 导出 SQL 表并将其与关系组合
- html - 为什么@media print (div) 中的属性不起作用?
- sql - 按年和月填充空白 SQL 行
- python - 我无法从其他位置查询任何内容
- c++ - 将特征向量序列化为 QDataStream
- android - Android Studio 的 Fabric 插件不断让我退出