mongodb 如何循环遍历JSON对象数组?

wnrlj8wa  于 2022-12-22  发布在  Go
关注(0)|答案(3)|浏览(179)

我需要遍历JSON数据,数据位于一个名为“people.json”的文件中,其结构如下所示:

[{"firstname":"John","lastname":"Smith","age":"40"},{"firstname":"Bill","lastname":"Jones","age":"40"}, ...]

我想读取这个文件中的每个对象并保存它(我使用的是Mongoose)。

var fs = require('fs');
var Person = require('../models/people');

fs.readFile('./people.json', 'utf8', function (err,data) {
    var i;
    for(i = 0; i < data.length; i++) {
        var newPerson = new Person();
        newPerson.firstname = data[i].firstname;
        newPerson.lastname = data[i].lastname;
        newPerson.age = data[i].age;
        newPerson.save(function (err) {});
    }
});

我还是不能让它工作。我做错了什么?

5vf7fwbs

5vf7fwbs1#

fs.readFile('./people.json', 'utf8', function (err,data) {
  data = JSON.parse(data); // you missed that...
  for(var i = 0; i < data.length; i++) {
    var newPerson = new Person();
    newPerson.firstname = data[i].firstname;
    newPerson.lastname = data[i].lastname;
    newPerson.age = data[i].age;
    newPerson.save(function (err) {});
  }
});
zkure5ic

zkure5ic2#

ES6 for..of也可以做到这一点。

fs.readFile('./people.json', 'utf8', function (err,data) {
  for(var item of data) {
     console.log('item: ', [item.firstname, ...]);
  }
});
tcbh2hod

tcbh2hod3#

const parsedData = JSON.parse(JSON.stringify(data));

相关问题