5

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:

    var Chooser = require('../chooser');

    var appRouter = function(app) {

    app.put("/chooser/:id", function(req, res) {
    console.log("ID: ", req.params.id);
    if (!req.body.toFollow) {
        return res.send({"status": "error", "message": "The account that you want to follow is needed"});
    }
    else {
        console.log("Cuenta: ", req.body.toFollow);
        Chooser.update({_id: req.params.id}, {$push: {accounts: {"name": "foo", "idAccount": 123456}}});
        return res.send({"status": "ok"});
    }

  });
}

This is my mongoose schema. Chooser.js:

var mongoose = require('mongoose');

var chooserSchema = mongoose.Schema({
_id: Number,
accounts: [{name: String, idAccount: Number}]
}, { _id: false });

var Chooser = mongoose.model('Chooser', chooserSchema);

module.exports = Chooser;
isanma
  • 165
  • 1
  • 2
  • 12
  • Does "Cuenta" log to the console? Also, don't you want to res.send after the .update i.e. in a callback function of update ? – George Apr 09 '18 at 21:24
  • See https://stackoverflow.com/questions/14877967/mongoose-doesnt-update-my-document-if-i-have-no-callback-function – JohnnyHK Apr 09 '18 at 21:25
  • Does this answer your question? [Array.push does not seem to work on MongoDB](https://stackoverflow.com/questions/58432171/array-push-does-not-seem-to-work-on-mongodb) – A.K. Jan 30 '20 at 10:26

4 Answers4

7

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
                   })
Nikhil Savaliya
  • 2,138
  • 4
  • 24
  • 45
Naimish Kher
  • 284
  • 1
  • 9
1

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);
    });
S. Hussey
  • 377
  • 1
  • 3
  • 11
1

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

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

Deeksha Sharma
  • 3,199
  • 1
  • 19
  • 16