如何从一个集合中检索值并将其添加到另一个集合中.. Mongoose,Node JS

How to retrieve and add the value from one collection to another.. Mongoose , Node JS

Asset 和 Assetlist 是两个不同的集合。如果创建了资产列表,我想将资产列表的数量添加到资产数量。谁能建议如何实现这一点..

app.post("/assetlists/new", function(req, res){
   var astname = req.body.astname;
   var brand = req.body.brand;
   var quantity1 = req.body.quantity;
   var purchasedate = req.body.purchasedate;
   var newAssetlist = {astname: astname, brand: brand, quantity: quantity, purchasedate: purchasedate};
   Assetlist.create(newAssetlist, function(err, newlyCreated){
       if(err){
           console.log(err);
       } else{
           res.redirect("/assetlists");
           console.log("Working create");
       }
   });
   
   Asset.findOneAndUpdate({ name: astname }, {$set:{ quantity: quantity1}}, function(err, updatedAssetquantity){
        if(err){
            console.log(err);
        } else {
        
        }
    });
});

试试这个代码:

这里我们在更新查询中使用了$inc。在创建 AssetList 后的回调中调用 Update 查询。

app.post("/assetlists/new", function (req, res) {
    var astname = req.body.astname;
    var brand = req.body.brand;
    var quantity1 = req.body.quantity;
    var purchasedate = req.body.purchasedate;
    var newAssetlist = {astname: astname, brand: brand, quantity: quantity, purchasedate: purchasedate};
    Assetlist.create(newAssetlist, function (err, newlyCreated) {
        if (err) {
            console.log(err);
        } else {
            console.log("Working created", newlyCreated);
            Asset.findOneAndUpdate({name: astname}, {$inc: {quantity: 1}}, function (err, updatedAssetquantity) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("updatedAssetquantity", updatedAssetquantity);
                    res.redirect("/assetlists");
                }
            });
        }
    });
});

希望对您有所帮助。