我尝试从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,,,,,
1条答案
按热度按时间qvtsj1bj1#
确保正确建立了数据库连接。
如果是这种情况,你应该
await
两个save()
调用。此外,你可以使用create
来生成你需要的city._id
: