0

I currently have a schema which looks as follows:

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

I also have 3 objects which I need to insert into my database:

enter image description here

How can I insert these into my database through an Ajax call? What Ive tried so far:

Adding the data to an array like this:

["58d6b7e11e793c9a506ffe8f", 0, "58c2871414cd3d209abf4fc1", 1, "58d6b7e11e793c9a506ffe7f", 1]

Which would then be passed through my ajax call like this?(unsure)

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

Inserting into the database is where I'm stuck, how do I break down the array in order to insert it?

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

      User.update(
        { "_id": req.user._id},
        { "$push":
            {"positionsApplied":
                {
                // unsure what to do here?

                }
            }
        }
    ).exec(function (err, result) {
           console.log(result);
           res.send({ results: result });
      });
      });

Any help is greatly appreciated! * Note the position_id field in the schema is the div_id in the array, also the index-position field is the index_pos in the array.

user schema:

    var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var User = new Schema({
    id: String,
    name: String,
    companyname: String,
    password: String,
    email: String,
    username: String,
    location: String,
    role:String,
    teamwork:Number,
    initiative:Number,
    technical_skills: Number,
    communication:Number,
    employees: String,
    profile_image: String,
    biodescription: String,
    twitter: String,
    facebook: String,
    instagram: String,
    linkedin: String,
    biodescription: String,
    positionsApplied:[{
                            position_id:String,
                            index_position: Number
    }],
    experience: [{
          title: String,
          location: String,
          company: String,
          start: String,
          end:String,
          description:String
  }],
    position: [{
                    _id:String,
          title: String,
          location: String,
          start: String,
          term:Number,
          description:String,
          date: {type: Date, default: Date.now},
          applied:[{
                candidate_id: String,
                profile_image: String,
                location: String,
                name: String,
                _id:String
                        }],
  }],
  education: [{
          school: String,
          location: String,
          degree: String,
          start: String,
          end:String,
          description:String,
                    _id:String
  }],

    images: [{
                    one: String,
                    two: String,
                    three: String,
                    four: String,
                    five:String,
                    six:String
    }],
});


module.exports = mongoose.model('User', User);

enter image description here

user
  • 395
  • 2
  • 11
  • 28

1 Answers1

0

Since your Schema is an array of objects and the data that you are getting(as per console of the browser) is also an array of objects why don't you just pass that array itself(the one in the console of the browser) through ajax and use the $each of mongodb $push to save it into the database.

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

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

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

You will have to change the arrayOfObjects keys to match that of your schema positionsApplied keys.

Hardik Jain
  • 184
  • 8
  • for some reason I'm getting "Unexpected token :" and its referencing the "$each: object" line, am I missing something? – user Apr 18 '17 at 18:56
  • Thanks! I'm getting back a completely blank object when I run that, however in the console I'm getting ---> "UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: The argument to $each in $push must be an array but it was of type NULL" – user Apr 18 '17 at 19:22
  • Does the `arrayOfObjects` come into your post route? Check what comes in the `console.log(req.body.arrayOfObjects)`. Is it NULL? – Hardik Jain Apr 18 '17 at 19:29
  • The position_id's are all part of subdocuments in a Users collection, I have updated the question to show my users schema. when I log that in the console I get back the entire document to which the position_id belongs to .. so I'm basically getting back 3 users, because I have 3 documents. – user Apr 18 '17 at 19:39
  • However the error message I posted above is still there at the end of the log! – user Apr 18 '17 at 19:41
  • So you could go one level further down, like `req.body.arrayOfObjects.positionsApplied`. But the image that you posted only contains `div_id` and `index_pos`. Anyway could you show me what comes up in the `console.log(req.body.arrayOfObjects)`. Even one row of it would be fine. I just want to check the structure. – Hardik Jain Apr 18 '17 at 19:53
  • I have updated the question with a photo of the console :) thats just one object being returned to me, as can be seen the position section is a sub document (this is where the position_id is coming from) – user Apr 18 '17 at 20:01
  • So basically what I have is a jQuery Sortable list of divs, and each div has an id (which is the position_id) and an index value (depending on where the div is in the list). When I click a save button it gets the order of the list and returns the object as seen in the image you just referenced, which includes the position_id along with its index_pos .. so my main goal here is to enter the objects into my database :) @Hardik Jain – user Apr 18 '17 at 20:26