我有一个集合‘事务’,有一对多的关系与文件引用的另一个集合‘库存’。我正在尝试编写一个函数,在添加事务时,查找当前的库存数量,以查看是否有足够的资金来完成事务。如果存在,则减去所需的库存(也称为更新集合)来完成事务。
事务收集
db.transaction.find({"_id":"transaction_3"},{"_id":0,"inventory":1})
{ "inventory" : [ { "inventory_id" : "inv_9", "stock" : 488 }, { "inventory_id" : "inv_10", "stock" : 102 }, { "inventory_id" : "inv_11", "stock" : 614 } ] }存货收集
db.inventory.find({"_id": "inv_9"}, {"stock":1})
{ "_id" : "inv_9", "stock" : 7151844 }如何循环遍历事务列表,获取库存id和所需库存数量,然后转到库存集合以减去它?
任何帮助都是非常感谢的。
发布于 2019-07-23 22:31:00
你是在找这样的东西吗?
库存文件:
{"_id":"inv_9","stock":1213574,"desc":"This is widget 9"}
{"_id":"inv_10","stock":25,"desc":"This is Widget 10"}
{"_id":"inv_11","stock":5510381,"desc":"This is widget 11"}交易文件:
{
"_id":"transaction_3",
"desc":"Sample Transaction 3",
"inventory":[
{"inventory_id":"inv_9","stock":488},
{"inventory_id":"inv_10","stock":102},
{"inventory_id":"inv_11","stock":614},
{"inventory_id":"not_there","stock":90000000}
]
}处理事务和循环库存数组的代码,以更新每个库存文档。这应该提供足够的信息来根据您的要求创建验证步骤(不确定您是在执行“全部或无”或“任何”类型的更新)。
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
async function invUpdate() {
const client = await MongoClient.connect(url, {useNewUrlParser: true})
.catch(err => {
console.log(err);
});
if (!client) {
return;
}
try {
const db = client.db("mrp");
let inv = db.collection('inv');
let trans = db.collection('trans');
let query = {};
const trx = await trans.find(query).forEach(function (item) {
item.inventory.forEach(async function (order) {
let reduceBy = order.stock * -1;
const updInv = inv.updateOne({_id: order.inventory_id, stock: {$gte: order.stock}},
{$inc: {stock: reduceBy}});
updInv.then((good) => {
if (good.result.nModified === 1) {
console.log(`Success, Inventory id ${order.inventory_id} was reduced by ${order.stock} `);
} else {
console.log(`Unable to update ${order.inventory_id}`);
}
});
updInv.catch((bad) => {
console.log('Something did go right ' + bad)
})
});
}
);
} catch
(err) {
console.log(err);
} finally {
client.close();
}
}
invUpdate();产出:
成功后,库存id inv_9减少了488。 无法更新inv_10 成功后,库存id inv_11减少了614。 无法更新not_there
https://stackoverflow.com/questions/57168210
复制相似问题