【问题标题】:MongoDB Error 'Cannot read property '_id' of undefined'MongoDB错误'无法读取未定义的属性'_id''
【发布时间】:2019-11-14 18:49:15
【问题描述】:

我正在为教师和他们的学生设置一个带有聊天室的网络应用。教师将邀请他们的学生参加该计划,因此我需要验证学生是否已经拥有一个帐户。

我已经在互联网上搜索了解决方案,但没有一个解决方案与我的问题相同

function insertUsers(collectionName, userArray) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('squeakdb');
        for (var i=0; i<userArray.length; i++) {
            dbo.collection(collectionName).find({ studentId: userArray[i].studentId }).toArray(function (err, res) {
                console.log(res == '');
                // If res == '' is true, it means the user does not already have an account
                if (res == '') {
                   dbo.collection(collectionName).insertOne(userArray[i], function(error, result) {
                       if (error) throw error;
                       console.log('Inserted'); 
                   }); 
                }
            });
        }
    });
}
insertUsers('userlist', [{ 'studentId': 'STU0001' }, { 'studentId': 'STU0018', 'firstName': 'testName' }]);

预期结果是数组中的第一个对象不插入数据库,而第二个对象插入。

当前结果是第一个对象未​​插入(如预期的那样),第二个对象产生以下错误:

TypeError:无法读取未定义的属性“_id”

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

我发现了错误发生的原因,它是由在 for 循环中执行异步调用引起的。这是固定的代码。

function insertUsers(collectionName, userArray) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db('squeakdb');
        userArray.forEach(function (index){
            dbo.collection(collectionName).find({ studentId: index.studentId }).toArray(function (err, res) {
                console.log(res.length == 0);
                if (res.length == 0) {
                   dbo.collection(collectionName).insertOne(index, function(error, result) {
                       if (error) throw error;
                       console.log('Inserted'); 
                   }); 
                }
            });
        });
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2019-07-28
    • 2017-06-15
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2022-07-27
    • 2013-09-03
    相关资源
    最近更新 更多