【发布时间】: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”
【问题讨论】:
-
那个帖子里的解决方法不行,我已经试过了
-
错误出现在哪一行?旁注,
res应该是一个数组。最好检查length属性,而不是与空字符串进行比较。 -
第10行出现错误
-
可能是因为你试图在 for 循环中进行异步调用,看看这个:stackoverflow.com/questions/11488014/…
标签: javascript node.js mongodb