简体   繁体   English

如何使用nodejs修复这个foreach函数错误

[英]How to fix this foreach function error with nodejs

I have a nodejs script allowing me to insert data contained in json files on Firestore, but after execution I have a function not found error.我有一个 nodejs 脚本,允许我在 Firestore 上插入包含在 json 文件中的数据,但执行后我有一个未找到函数的错误。 How can I fix this situation?我该如何解决这种情况? Thanks Here is all my code:谢谢这是我所有的代码:

var admin = require("firebase-admin");

var serviceAccount = require("./service_key.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://xxxxxxxxx.firebaseio.com"
});

const firestore = admin.firestore();
const path = require("path");
const fs = require("fs");
const directoryPath = path.join(__dirname, "files");

fs.readdir(directoryPath, function(err, files) {
  if (err) {
    return console.log("Unable to scan directory: " + err);
  }

  files.forEach(function(file) {
    var lastDotIndex = file.lastIndexOf(".");

    var menu = require("./files/" + file);

    menu.forEach(function(obj) {
      firestore
        .collection(file.substring(0, lastDotIndex))
        .doc(obj.itemID)
        .set(obj)
        .then(function(docRef) {
          console.log("Document written");
        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        });
    });
  });
});

I have this mistake to send back:我有这个错误要发回:

/Users/nana/Documents/SCRIPT/uploader.js:25
    menu.forEach(function(obj) {
         ^

TypeError: menu.forEach is not a function
    at /Users/nana/Documents/SCRIPT/uploader.js:25:10
    at Array.forEach (<anonymous>)
    at /Users/nana/Documents/SCRIPT/uploader.js:20:9
    at FSReqCallback.oncomplete (node:fs:188:23)

From what I can tell menu isn't an array.据我所知, menu不是数组。 You are simply requiring a file inside the path of './files/' .您只requiring './files/'路径内的文件。

Try console.log(typeof menu) to see what the terminal says menu is.试试console.log(typeof menu)看看终端说的 menu 是什么。 But to me it doesn't look like an array.但对我来说,它看起来不像一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM