我成功地从远程服务器获取JSON对象。 JSON文件是对象数组。我遍历它们,并在循环中尝试使用猫鼬保存每个文档对象,如下所示。但是,在500条记录中,只有50条记录被保存。所以很明显,我在async / await中做错了什么。感谢您的帮助。
编辑:根据用户的要求添加了更多代码。
const mongoose = require('mongoose')
const fetch = require('fetch-json')
const PriceModel = mongoose.model('Price', priceSchema);
getPrices = async () => {
try {
const url = 'https://api.binance.com/api/v3/ticker/price'
const params = ''
const jsonData = await fetch.get(url, params)
return jsonData
} catch (e) {
console.log('Error caught during getPrices: ', e.message)
}
}
mongoose.connect('mongodb://localhost/prices', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('we\'re connected')
});
const priceSchema = new mongoose.Schema({
timestamp: Date,
symbol: String,
price: Number
});
persistData = async () => {
try {
const timestamp = Date.now()
const allPrices = await getPrices()
for (const element of allPrices) {
let doc = new PriceModel()
doc.timestamp = timestamp
doc.symbol = element.symbol
doc.price = element.price
await doc.save()
}
} catch (e) {
console.log('Error caught during db save: ', e.message)
}
}
答案 0 :(得分:3)
从4.4版开始,猫鼬支持insertMany操作。因此,一种更快的算法将是准备所需的数据:
const priceModels = [];
for (const element of allPrices) {
let doc = {
timestamp,
...element,
}
priceModels.push(doc)
}
在准备好所有对象之后,您需要对数据库进行一次插入:
await PriceModel.insertMany(priceModels);