假设我们有一个包含学生数据的数据库表,每个数据行包含学生的姓名和其分数。我们想要将这些数据保存到一个JavaScript数组中。以下是实现此目的的代码示例:
// 连接到数据库
const db = connect('localhost:27017/myDB');
// 获取学生数据
const students = db.students.find();
// 创建空数组
const studentArray = [];
// 将数据添加到数组中
while (students.hasNext()) {
const student = students.next();
studentArray.push({ name: student.name, score: student.score });
}
// 输出数组
console.log(studentArray);
上面的代码连接到本地MongoDB数据库,并获取名为“students”的数据库表中的所有数据行。然后,它创建一个空的JavaScript数组“studentArray”并使用while循环遍历数据行。在遍历循环中,将每个数据行的姓名和分数添加到数组中。最后,该程序输出完整的学生数组。
使用这种方法,我们可以将数据库中的数据保存到JavaScript数组中,使得数据更易于使用和操作。
下一篇:遍历数据库结果