gpt4 book ai didi

javascript - MongoDB 错误 'Cannot read property ' _id' of undefined'

转载 作者:可可西里 更新时间:2023-11-01 10:45:02 24 4
gpt4 key购买 nike

我正在为教师和他们的学生建立一个带有聊天室的网络应用程序。老师会邀请他们的学生参加该计划,因此我需要验证学生是否已有帐户。

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

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: Cannot read property '_id' of undefined

最佳答案

我发现了错误发生的原因,它是由在 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');
});
}
});
});
});
}

关于javascript - MongoDB 错误 'Cannot read property ' _id' of undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56880970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com