这个问题通常出现在使用 MongoDB Node.js 驱动程序的 findOne() 或 find() 方法时。解决方案是在回调函数中使用 toArray() 函数将数据转换为数组,然后才能使用 forEach() 方法遍历数据。以下是示例代码:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'myproject';
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
const collection = db.collection('documents');
collection.find().toArray(function(err, docs) {
docs.forEach(function(doc) {
console.log(doc);
});
client.close();
});
});