gpt4 book ai didi

node.js - Mongoose等待doc.save()不完整

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:41 26 4
gpt4 key购买 nike

我成功从远程服务器获取 JSON 对象。 JSON 文件是一个对象数组。我循环遍历它们,并在循环期间尝试使用 Mongoose 保存每个文档对象,如下所示。但 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)
}
}

最佳答案

从 4.4 版开始,mongoose 确实支持 insertMany手术。因此,更快的算法是准备您所需的数据:

const priceModels = [];

for (const element of allPrices) {
let doc = {
timestamp,
...element,
}
priceModels.push(doc)
}

准备好所有对象后,向数据库进行一次插入:

await PriceModel.insertMany(priceModels);

关于node.js - Mongoose等待doc.save()不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com