【问题标题】:I need to pass a JSON file to MongoDB using Mongoose我需要使用 Mongoose 将 JSON 文件传递​​给 MongoDB
【发布时间】:2020-09-21 04:16:58
【问题描述】:

我试过这个,但它不起作用: readFile 运行良好,它在与数据库的连接开始之前完成。 我的问题是尝试使用 Mongoose 将解析的 JSON obj (listingData) 用于 MongoDB。

 let listingData;
 fs.readFile('listings.json', 'utf8', (err, data) => {
   try {
     listingData = JSON.parse(data);
   } catch (err) {
     console.log('Error reading JSON file');
     throw err;
   }
   //console.log(listingData); // PRINTS DATA CORRECTLY!
 });

 async function loadListings() {
   try {
     await Listing.insertMany(listingData); // imported.insertMany(JSON Parsed)
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.log("Error importing listings to DB");
     process.exit();
   }
 }

已解决,谢谢

【问题讨论】:

    标签: node.js json mongodb mongoose


    【解决方案1】:

    readFile 和 loadListings 都是异步的,因此 loadListing 不会等待 readFile 完成并传递数据,因为到那时 listingData 是undefined。

    你可以使用fs的promise库来解决这个问题。 node 10.x版本后可用

      const fs= require(fs).promises
    
    async function loadListings() {
       try {
         let listingData= await fs.readFile('listings.json','utf8')// Get data here, await will wait for execution to finish
         await Listing.insertMany(listingData);
         console.log("Listings inserted in the DB");
         //process.exit();
       } catch (error) {
         console.error(error) // Catch Error here
         console.log("Error importing listings to DB");
         process.exit();
       }
     }
    

    【讨论】:

    • 谢谢,以不同的方式解决它,但会检查 Promises 以正确完成。
    【解决方案2】:

    如果您检查 fs.readfile,您会注意到它是一个异步函数。

    所以加载列表不会等待 readfile 完成。

    有两种方法可以解决此问题,一种不好的方法和一种好的方法。

    不好的方法是让您从加载列表中删除异步,并将 readfile 转换为 readfilesync。这是 BAD 因为它是 不是 node.js 方式...尽可能异步。

    相反,您应该通过将readfile INTO 加载列表作为一个承诺来学习如何正确利用异步。这是@Shivam Sood 给你的解决方案。

    【讨论】:

    • 我尝试了选项 1(错误的选项),它运行了。不正确。我用简单的方法解决了它,只是将插入移动到 readFile 的末尾。谢谢你的解释,我还在学习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多