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

时间:2018-06-28 13:15:55

标签: javascript node.js mongodb mongoose simultaneous

资产和资产列表是两个不同的集合。如果创建了资产清单,我想将资产清单的数量添加到资产数量中。有人可以建议如何实现此目标。

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 {
        
        }
    });
});

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

在这里,我们在更新查询中使用 $ 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");
                }
            });
        }
    });
});

希望这对您有所帮助。