Thursday, 20 April 2017

Insert object into MongoDB subdocument

I currently have an array which is as follows (this is names arrayOfObjects)

enter image description here What I need to do is insert this object into my mongodb database using mongoose. However I cant seem to get the insert to work.

Here is the section of my schema which represents where the data should be entered:

positionsApplied:[{
        position_id:String,
        index_position: Number
}],

Ajax Call:

$.ajax({
                   url: "/insertPositionIndex",
                   type: "POST",
                   dataType: "json",
                   data: {
                      arrayOfObjects
                   },
                   success: function (data) {
                      console.log(data);

                }
              })

and my post request:

      app.post('/insertPositionIndex', function(req, res){
  var object = req.body.arrayOfObjects;
  console.log(req.body.arrayOfObjects);

  User.update(
   { "_id": req.user._id},
     {
     "$push":
         {
          "positionsApplied":{
             "$each": req.body.arrayOfObjects
            }
         }
   }
      ).exec(function (err, result) {
          //   console.log(result);
             res.send({ results: result });
        });
  });

But When I run this code, and try to log the data returned to the ajax call I get :

    undefined
(node:1456) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: The argument to $each in $push must be an array but it was of type Object

Anyone know what I'm doing wrong?



via user

No comments:

Post a Comment