简体   繁体   中英

return pushed object's id nodejs mongoose

I have object array(batches) inside a document(products).
after pushing a new object to that array, I want to return only the newly added object's auto-generated ID in the axios post response. please how to do that?

batchRoutes.route('/add/:id').post(function(req,res){
    Product.findOneAndUpdate(
        {"_id":req.params.id},
        {$push:{"batches":req.body}},

        function(err,batch){
            if(err){
                return res.json({'status':false});
            }
            else{
              return res.json({'status':true});
            }

        });
});

schema

let Product= new Schema({
    productName:{
        type:String
    },
    batches:[{    
            batchNo:{
                type:String
            },
            expDate:{
                type:Date
            },

    }]
},

You can access the updated document using the {new: true} option, and the last id in the document batches array is the newly generated id.

So the changes are:

1-) add { new: true } option as 3rd parameter

2-) get the last generated id: const batchId = doc.batches[doc.batches.length - 1]._id;

batchRoutes.route("/add/:id").post(function (req, res) {
  Product.findOneAndUpdate(
    { _id: req.params.id },
    { $push: { batches: req.body } },
    { new: true },
    function (err, doc) {
      if (err) {
        return res.json({ status: false });
      } else {
        if (doc) {
          const batchId = doc.batches[doc.batches.length - 1]._id;
          return res.json({ status: true, batchId });
        } else {
          return res.status(404).json({ status: false });
        }
      }
    }
  );
});

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