我想知道是否有更好的方法来更新数组中的现有元素,而不是三次获取数据库。如果您有任何想法,我将不胜感激。谢谢!
const creatStock = async (symbol, webApiData) => {
try {
// reversed array
const webApiDataReversed = webApiData.reverse();
const query = { symbol };
const update = { $addToSet: { data: webApiDataReversed } };
const options = { upsert: true, new: true };
// create/update Stock
const stockResult = await Stock.findOneAndUpdate(query, update, options);
const lastElement = stockResult.data.length - 1;
const updatePull = {
$pull: { data: { date: stockResult.data[lastElement].date } },
};
// removes last date from data array
await Stock.findOneAndUpdate(query, updatePull);
// update Stock
await Stock.findOneAndUpdate(query, update);
} catch (ex) {
console.log(`creatStock error: ${ex}`.red);
}
};
架构
const ChildSchemaData = new mongoose.Schema({
_id: false,
date: { type: mongoose.Types.Decimal128 },
open: { type: mongoose.Types.Decimal128 },
high: { type: mongoose.Types.Decimal128 },
low: { type: mongoose.Types.Decimal128 },
close: { type: mongoose.Types.Decimal128 },
volume: { type: mongoose.Types.Decimal128 },
});
const ParentSchemaSymbol = new mongoose.Schema({
symbol: {
type: String,
unique: true,
},
// Array of subdocuments
data: [ChildSchemaData],
});
module.exports.Stock = mongoose.model('Stock', ParentSchemaSymbol);
输出
答案 0 :(得分:1)
好吧,如果您不需要返回更新的文档,请尝试执行此操作-这将仅返回写入结果,并且可以通过一个DB调用来实现:
const creatStock = async (symbol, webApiData) => {
try {
// reversed array
const webApiDataReversed = webApiData.reverse();
const query = { symbol };
await Stock.bulkWrite([
{
updateOne:
{
"filter": query,
"update": { $pop: { data: 1 } }
}
}, {
updateOne:
{
"filter": query,
"update": {
$addToSet: {
data: webApiDataReversed
}
}
}
}
])
} catch (ex) {
console.log(`creatStock error: ${ex}`.red);
}
};
答案 1 :(得分:0)
您可以这样操作:
const creatStock = async (symbol, webApiData) => {
try {
// reversed array
const webApiDataReversed = webApiData.reverse();
const query = { symbol };
let stock = await Stock.findOne(query);
if(stock){
let stockData = JSON.parse(JSON.stringify(stock.data));
if(stockData.length>0){
stockData.pop();
}
stockData.concat(webApiDataReversed);
stock.data = stockData;
await stock.save();
}
} catch (ex) {
console.log(`creatStock error: ${ex}`.red);
}