mongodb 创建城市时出错MongooseError:操作`countries.findOne()`缓冲在10000毫秒后超时

t1qtbnec  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(135)

我尝试从csv文件以编程方式上传到mongodb。我已经尝试了所有其他解决方案,并确保我的ip被列入白名单,连接正确建立。
我仍然得到这个错误:创建城市时出错MongooseError:操作countries.findOne()缓冲在10000 ms后超时
下面是我的代码,我运行它从命令行.

const csv = require('csv-parser');
const fs = require('fs');

//const geocoder = mbxClient({ accessToken: 'YOUR_ACCESS_TOKEN_HERE' });
const { Country } = require('../models/country');
const { City } = require('../models/city');
const { Overall } = require('../models/overall');
const mbxClient = require("@mapbox/mapbox-sdk/services/geocoding");

const mapboxToken = process.env.MAPBOX_TOKEN;

const geocoder = mbxClient({ accessToken: mapboxToken });

const createCity = async ({ location, country, description, cjLink }) => {
    const creator = '641e6851ad1041163852d500';
    const images = [];
    console.log(country)
   try {
      const geoData = await geocoder
        .forwardGeocode({
          query: location,
          limit: 1,
        })
        .send();
      const geometry = geoData.body.features[0].geometry;
 
      const newCountry = await Country.find({ name: country });
    if (!newCountry) {
      console.log('Country not found');
      return null;
    }

      const city = new City({
        creator,
        location,
        geometry,
        country: newCountry[0]._id,
        url: '',
        cjLink: '',
        description: '',
      });
  
      const overall = new Overall({
        name: location,
        creator,
        location,
        geometry,
        country: newCountry[0]._id,
        url: '',
        cjLink: '',
        description: '',
      });
  
    
  
      overall.url = `/cities/${city._id}`;
      city.url = `/cities/${city._id}`;
      overall.save();
      city.save();
  
      return city;
    } catch (error) {
      console.log("error during create city", error);
      return null;
    }
};

  
const importCitiesFromCSV = async (filePath) => {
    try {
      const csvData = fs.readFileSync(filePath, 'utf-8');
      const rows = csvData.trim().split('\n');
      const headers = rows.shift().split(',');
      const cities = rows.map(row => {
        const values = row.split(',');
        return headers.reduce((obj, header, index) => {
          obj[header] = values[index];
          return obj;
        }, {});
      });
  
      for (let i = 0; i < cities.length; i++) {
        const { location, country, description, cjLink } = cities[i];
        const newCity = await createCity({ location, country, description, cjLink });

        if (newCity) {
          console.log(`Created city: ${newCity.location}`);
        }
      }
  
      console.log('Finished importing cities.');
    } catch (error) {
      console.log('Error importing cities from CSV', error);
    }
  };
  
  

// Example usage:
importCitiesFromCSV('./testData.csv');

下面是csv,只是一些示例数据来测试它:

位置,,名称,,国家/地区,,描述,,cjLink“Calgary,阿尔伯塔,Canada”,,Canada,,,“渥太华,安大略,Canada”,,Canada,,,,,

qvtsj1bj

qvtsj1bj1#

确保正确建立了数据库连接。
如果是这种情况,你应该await两个save()调用。此外,你可以使用create来生成你需要的city._id

const createCity = async ({ location, country, description, cjLink }) => {
  const creator = '641e6851ad1041163852d500';
  const images = [];
  console.log(country);
  try {
    const geoData = await geocoder
      .forwardGeocode({
        query: location,
        limit: 1,
      })
      .send();
    const geometry = geoData.body.features[0].geometry;

    const newCountry = await Country.find({ name: country });
    if (!newCountry || !newCountry.length) {
      console.log('Country not found');
      return null;
    }

    const city = await City.create({
      creator,
      location,
      geometry,
      country: newCountry[0]._id,
      url: '',
      cjLink: '',
      description: '',
    });

    const overall = await Overall.create({
      name: location,
      creator,
      location,
      geometry,
      country: newCountry[0]._id,
      url: '',
      cjLink: '',
      description: '',
    });

    overall.url = `/cities/${city._id}`;
    city.url = `/cities/${city._id}`;
    
    await overall.save();
    await city.save();

    return city;
  } catch (error) {
    console.log('error during create city', error);
    return null;
  }
};

相关问题