Mongodb TypeError:无法读取属性'_id';insertOne上未定义文档的定义

Mongodb TypeError:无法读取属性'_id';insertOne上未定义文档的定义,mongodb,express,Mongodb,Express,抛出此错误时,我正试图将记录插入集合。我在上查看了mongodb文档,我知道mongod在没有像我的情况那样指定时会自动添加_id,所以我想知道为什么会出现未定义的id错误 下面是我正在使用的代码,首先是api路由和我试图插入的数据 app.post('/api/contacts', (req, res) => { // retrieve the user being added in the body of the request const user = req.body; // o

抛出此错误时,我正试图将记录插入集合。我在上查看了mongodb文档,我知道mongod在没有像我的情况那样指定时会自动添加_id,所以我想知道为什么会出现未定义的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时,我遇到过类似的错误)

面临类似的问题。通过使用body parser,然后按如下方式解析发送的json对象,解决了此问题:

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

app.use(bodyParser.json());

// parse application/json
app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

我接受了建议,通过评论
const user=req,body
out下面的所有内容来查看
req.body
发送的内容,然后添加了
return res.json(user)
,并与邮递员一起测试了一篇帖子,用户的定义与您建议的不同,因为没有出现任何问题。所以现在的问题是如何获得用户定义?你知道吗?你想要的身体是什么形式的(postman允许你使用任何一种形式的数据,x-www-form-urlencoded,raw,binary),然后确保你已经正确地设置了身体解析器,如果你确实在使用身体解析器的话。(我通常剪切并粘贴设置,有时新的使用会出错,我会得到未定义的req.body)。最终找到了解决方案。通过将应用程序设置为使用主体解析器