简体   繁体   中英

MongoDB function - reference collection and update value

I have a collection 'transactions' that has a one-to-many relationship with document reference to another collection 'inventory'. I am trying to write a function that, when adding a transaction, looks up the current amount in-stock to see if there is enough to fulfill the transaction. If there is, then subtract the needed stock (aka update the collection) to complete the transaction.

Transaction collection

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 } ] }

Inventory collection

db.inventory.find({"_id": "inv_9"}, {"stock":1})

{ "_id" : "inv_9", "stock" : 7151844 }

How do I loop through the transaction list, grab the inventory id and amount of stock required, then go to the inventory collection to subtract it?

Any help is much appreciated.

Are you looking for something like this:

Inventory Docs:

{"_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"}

Transaction Doc:

{
    "_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}
        ]
}

Code to process transactions and loop inventory array updating each inventory document. This should provide enough info to create the validation steps as per you requirements (not sure if you are doing "all or none" or "any" type of update).

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();

Outputs:

Success, Inventory id inv_9 was reduced by 488

Unable to update inv_10

Success, Inventory id inv_11 was reduced by 614

Unable to update not_there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM