gpt4 book ai didi

javascript - 从循环内更新数据

转载 作者:行者123 更新时间:2023-12-03 04:02:35 24 4
gpt4 key购买 nike

我正在尝试让我的nodejs Controller 更新货币表中的汇率

在 S3T/RoboMongo 中一切正常,但由于某种原因它不会触发 Nodejs Controller 内的更新。

这是我的货币

{ 
"_id" : "USD",
"index" : NumberInt(6),
"name" : "Dollar",
"currency" : "USD",
"symbol" : "$",
"active" : true,
"default" : false,
"rate" : 0
}
{
"_id" : "EUR",
"index" : NumberInt(2),
"name" : "Euro",
"currency" : "EUR",
"symbol" : "€",
"active" : true,
"default" : false,
"rate" : 0
}

我尝试了这两个,在 S3T 中工作正常,但在 Nodejs 中不行:

db.currency.update (
{ _id : "EUR" },
{ $set: { rate : 123 }},
{ upsert: true }
)

db.currency.updateOne (
{ _id : "EUR" },
{ $set: { rate : 123 }},
{ upsert: true }
)

这是我的nodejs代码:

var mongoose = require('mongoose');
var currencyModel = require('../models/currencyModel');
var currencyTable = mongoose.model('currencyModel');
var updateRates = () => {
return new Promise((resolve, reject) => {
for (var key in data.quotes) {
var currencyID = key.substring(3);
var newRate = (data.quotes[key] * THBUSD).toFixed(5);
console.log("currencyID: " + currencyID)
console.log("newRate: " + newRate)

currencyTable.update (
{ _id: currencyID },
{ $set: { rate : newRate }},
{ upsert: true }
),function (err, data) {
if (err) {
reject(new Error('updateRates: ' + err));
};
};
};
resolve();
})};

这是我的currencyModel(我认为问题出在哪里?!?)

// Currency Model
// This model is the structure containing data from the Currency table
//
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var currencySchema = new Schema({
_id: String, // Unique Currency code
index: Number, // Indes for sorting
name: String, // Currency name
symbol: String, // Currency symbol
active: Boolean, // Active True False
rate: Number // Exchange rate (multiply with THB price)
});
module.exports = mongoose.model('currencyModel', currencySchema, 'currency');

我不明白为什么它不会从nodejs内部触发currencyTable.update。

我在 mongoose 中打开了调试,并且在控制台中看到了所有其他 mongodb 操作,例如 Mongoose:price.findOne({ _id: 'ATL-D406' }, { fields: {} }) 等等..但我在控制台中没有看到这个 currency.update ,这就是为什么我不认为它被触发到 mongodb - 而且我看不到原因。

最佳答案

您有一个“循环”,它在内部回调触发之前完成执行。相反,只需自始至终使用 Promise 并调用 Promise.all()收集所有迭代的 Promise 并解决它们:

var updaterates = () => {
return Promise.all(
Object.keys(data.quotes).map(k => {
return currencyTable.update(
{ _id: k.substring(0,3) },
{ $set: { rate : (data.quotes[k] * THBUSD).toFixed(5) }},
{ upsert: true }
).exec()
});
)
};

返回的响应Promise.all()是来自更新的响应对象的数组。另请注意,这是一个“快速失败”操作,并且调用将并行进行。

Object.keys()返回指定对象中的“键名称数组”。 .map()迭代这些键并返回迭代器的返回值的“数组”。

我们使用k作为“键名称”来从data.quotes访问所需的键,并使用这些值来执行每个.update().exec()返回“真实”Promise 。迭代器返回一个“数组”Promise这成为 Promise.all() 的参数.

关于javascript - 从循环内更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44661453/

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