mongodb 无法在 NodeJS 中移位()数组

6l7fqoea  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(117)

我可以将数组数据添加到mongo数据库中,但是由于某种原因,当我在myFile.on函数之外打印内容时,它显示为空。

function main() {

    mongoose.connect("mongodb+srv://username:password@cluster0.thojgej.mongodb.net/hw14").
        catch(error => handleError(error));

    var db = mongoose.connection;

    db.on('error', console.error.bind(console, 'connection error:'));

    db.once('open', function () {
        console.log("Connection Successful!");
    });

    var companyArr = [];

    var myFile = readline.createInterface({
        input: fs.createReadStream('companies.csv')
    });
    myFile.on('line', function (line) {
        let data = line.split(',');
        companyArr.push({
                name: data[0],
                ticker: data[1]
        });
    });
    **companyArr.shift();**
    var collection = db.collection('equities');
    collection.insertMany(companyArr, (err, res) => {
        if (err) throw err;
        db.close();
    });
    console.log('Full success!');
}

main();

它不会删除数组中的第一个元素,我希望有人能帮助我解决这个问题。

r55awzrz

r55awzrz1#

在流完成读取文件后,尝试使用close事件执行操作:

function main() {
  mongoose
    .connect(
      'mongodb+srv://username:password@cluster0.thojgej.mongodb.net/hw14'
    )
    .catch((error) => handleError(error));

  var db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error:'));

  db.once('open', function () {
    console.log('Connection Successful!');
  });

  var companyArr = [];

  var myFile = readline.createInterface({
    input: fs.createReadStream('companies.csv'),
  });
  myFile.on('line', function (line) {
    let data = line.split(',');
    companyArr.push({
      name: data[0],
      ticker: data[1],
    });
  });
  myFile.on('close', function () {
    companyArr.shift();

    var collection = db.collection('equities');
    collection.insertMany(companyArr, (err, res) => {
      if (err) throw err;
      db.close();
    });
    console.log('Full success!');
  });
}

main();

相关问题