首页 > 解决方案 > 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 上的数据库的数据库连接成功且没有错误。这里可能有什么问题,我该如何解决这个错误?

标签: mongodbexpress

解决方案


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


推荐阅读