类型错误:无法在 insertOne 的 insertDocuments 中读取未定义的属性“_id”

Men*_*ena 3 mongodb express

当抛出此错误时,我试图将记录插入集合中。我浏览了insertOne上的 mongodb 文档,我知道 mongod 会在未指定 _id 时自动添加 _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);
});
});
Run Code Online (Sandbox Code Playgroud)

用于插入的json数据

{
"name": "Wes Harris",
"address": "289 Porter Crossing, Silver Spring, MD 20918",
"phone": "(862) 149-8084",
"photoUrl": "/profiles/wes-harris.jpg"
}
Run Code Online (Sandbox Code Playgroud)

与 mlab 上托管的数据库的数据库连接成功,没有错误。这里可能出了什么问题,我该如何修复这个错误?

小智 5

该错误消息意味着您传递给 insertOne 的对象未定义(因此它可以\xe2\x80\x99t 读取它的 _id 属性)。您可能想查看 req.body 到底包含什么,因为这是作为用户传递的内容。(我不知道 TypeScript,但是在 Node/express 中,当我没有正确设置 bodyParser 时,我遇到了这样的错误)

\n