为什么我的外部 API 数据没有播种到 mongoose 中?

问题描述 投票:0回答:1

长时间休息后我将返回代码,所以我感谢您的耐心。我正在尝试将 Parks API 植入 Mongoose,但没有看到通过“parksData”JSON 在控制台中生成的文档。

我正在检索 API,因为我可以控制台记录对象并且我正确引用了模型。但是,当我尝试通过 for 循环重复每个公园以创建新文档时,就会出现该错误。 (没有实际的错误代码,但代码的行为与预期不同。它没有记录公园正在保存。)

下面是种子文件。我也会把模型放在下面。

const connection = require('../config/connection');
const { Park } = require('../models');
let saveCounter = 0;

function getData() {
    const parksAPI = "https://developer.nps.gov/api/v1/parks?&api_key=2e5oEbbGmJ48yr9eoR5qDC5S7k8Hif4f4ZaesDyt"
    fetch (parksAPI)
        .then(function (response) {
            if (!response.ok) {
                throw response.json();
            }
            return response.json();
        })
        .then(function (parksData) {
            // console.log("parksData", parksData);
            // console.log(Park.prototype);
            if (parksData) {
                for (let i = 0; i < parksData.length; i++) {
                let park = new Park({
                    id: parksData[i].id,
                    fullname: parksData[i].fullName,
                    description: parksData[i].description,
                    latitude: parksData[i].latitude,
                    longitude: parksData[i].longitude,
                    activities: parksData[i].activities,
                    states: parksData[i].states,
                    entranceFees: parksData[i].entranceFees,
                    entrancePasses: parksData[i].entrancePasses,
                    directionsInfo: parksData[i].directionsInfo,
                    directionsUrl: parksData[i].directionsUrl,
                    operatingHours: parksData[i].operatingHours,
                    addresses: parksData[i].addresses,
                    images: parksData[i].images,
                    weatherInfo: parksData[i].weatherInfo,
                    name: parksData[i].name,
                    designation: parksData[i].designation
                })

                park.save(() => {
                    console.log("saved" + park)

                    saveCounter++;

                    if (saveCounter === parksData.length) {
                        mongoose.disconnect()
                            .then(() => console.log("saved successfully and mongoose disconnected"))
                            .catch(error => console.log(error));
                        }
                });
            }
        }
            if (!parksData) {
                console.log("no results found :(")
            } 
        })
}


connection.on('error', (err) => err);

connection.once('open', async () => {
    console.log('connected');
    //drop existing users
    await Park.deleteMany({});
    getData();
})
const { Schema, model } = require('mongoose');

const parkSchema = new Schema({
    id: {
        type: Number,
        required: true,
    },
    fullname: {
        type: String,
        required: true,
    },
    description: {
        type: String,
    },
    latitude: {
        // needs to be decimal
        type: Number,
    },
    longitude: {
        type: Number
    },
    activities: [ {
        type: String
    }],
    topics: [ {
        type: String
    }],
    states: [ {
        type: String,
        required: true,
    }],
    entranceFees: [ {
        type: String,
        required: true,
    }],
    entrancePasses: [ {
        type: String,
        required: true,
    }],
    directionsInfo: {
        type: String
    },
    directionsUrl: {
        type: String
    },
    operatingHours: [ {
        type: String
    }],
    addresses: [ {
        type: String,
    }],
    images: [{
        type: String,
    }],
    weatherInfo: {
        type: String,
    },
    name: {
        type: String,
        required: true,
    },
    designation: {
        type: String,
        required: true,
    },
});

const Park = model('park', parkSchema)
module.exports = Park;

编辑:park.save() 编辑以查看是否可以找到错误,但在控制台中没有看到任何响应。

 park.save((err, result) => {
                if (err) {console.log(err)}
                else {
                    console.log("saved" + park);
                    saveCounter++;

                    if (saveCounter === parksData.length) {
                        mongoose.disconnect()
                            .then(() => console.log("saved successfully and mongoose disconnected"))
                            .catch(error => console.log(error));
                        }
                }
            });
javascript node.js mongoose seed
1个回答
0
投票

ReferenceError:未定义 fetch。这是代码中的错误。要调试此错误,请将代码放入 try catch 块中,如下所示。

connection.once('open', async () => {
    try {
        console.log('connected');
        //drop existing users
        await Park.deleteMany({});
        getData();
    } catch (error) {
        console.log("error :: ", error)
    }
})

修复此错误阅读本文

© www.soinside.com 2019 - 2024. All rights reserved.