Push element to array in mongoose

前端 未结 4 495
逝去的感伤
逝去的感伤 2021-01-20 07:42

I am trying to push an element to an array in mongoose. I am doing it with update and $push. But it is not updating it in the database. This is my code. routes.js:



        
相关标签:
4条回答
  • 2021-01-20 08:07

    This is how you can update a model in mongoose (using async await) :

    
    let updatedModel = await Model.findByIdAndUpdate(req.params.id,
    
     { $push: { accounts:{"name": "foo", "idAccount": 123456} } },
    
     { 'upsert': true });
    

    or in your code

    Maybe you have missed the {new: true, upsert: true } if you want the updated document to be returned to you.

    Chooser.update({_id: req.params.id}, {$push: {accounts: {"name": "foo", "idAccount": 123456}}},{new: true, upsert: true });
    
    
    0 讨论(0)
  • 2021-01-20 08:09

    We are doing it this way - we are adding another model but in your case your just adding an array so put that in a variable and in place of req.body.resource ..

    Also you can just use findByIdAndUpdate not the Async if you don't want to.

    here is the model element:

     resources: [{type: mongoose.Schema.Types.ObjectId, ref: 'Resource'}],
    

    here is the method to add an item to the array:

    //AddResource to a crew
    export function addResource(req, res) {
      if (req.body._id) {
        delete req.body._id;
      }
      Crew.findByIdAndUpdateAsync(req.params.id,
        {
          $push: { "resources": req.body.resource }
        },
        { safe: true, upsert: true },
        function (err, model) {
          if (err) {
            //console.log(err);
            return res.send(err);
          }
          return res.json(model);
        });
    

    and to remove:

    //deleteResource to a crew
    export function deleteResource(req, res) {
      if (req.body._id) {
        delete req.body._id;
      }
      // console.log(req.body.resource);
      Crew.findByIdAndUpdateAsync(req.params.id,
        {
          $pullAll: { "resources": req.body.resource }
        },
        function (err, model) {
          // console.log(model);
          if (err) {
            //console.log(err);
            return res.send(err);
          }
          return res.json(model);
        });
    
    0 讨论(0)
  • 2021-01-20 08:16

    We can do like that

    Model.findOneAndUpdate({"_id":req.body.id},{
                "$push": {"resources": req.body.resources}
            },{new: true, safe: true, upsert: true }).then((result) => {
                return res.status(201).json({
                    status: "Success",
                    message: "Resources Are Created Successfully",
                    data: result
                });
            }).catch((error) => {
                return res.status(500).json({
                    status: "Failed",
                    message: "Database Error",
                    data: error
                });
            });`
    
    0 讨论(0)
  • 2021-01-20 08:24

    As far as I know, you have to do as below.

    Model.findAndUpdate({_id: 'your_id'}, 
                        {$push: {'your_array_field': 
                        {"name": "foo","idAccount": 123456}}}, 
                        {new: true}, (err, result) => {
                        // Rest of the action goes here
                       })
    
    0 讨论(0)
提交回复
热议问题