Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am having an issue inserting a new JSON object into an array of JSON objects in MongoDB from my Angular Controller.

A simple concept of what I am trying to do is for this schema:

var ThingSchema = new mongoose.Schema({
   id: Number,
   items: [{
      item_id: Number,
      item_name: String,
      item_price: Number
   }]
});

And to add it to my mongodb in a the Mongo console I can use:

db.things.update( 
{ "_id": ObjectId("579b7860b168c80c1fe8a32a")},
{ $push: { 
    "items": {
        "item_id" : 134,
        "item_name" : "sampleItem",
        "item_price" : 234.00
    }}
})

However, I'm not sure how I can translate that over to an http request from AngularJS. I used Yeoman to scaffold my app and am more interested in getting a functional prototype right now. In my Angular Controller, I am using this function

addNewItem(thing, newItem) {
    this.$http.put('/api/things/' + thing._id, { 'items': newItem})
      // on success clear the fields
     .then( response => {
        console.log(response);
        alert(this.newItem);
        thing.items.push(newItem);
        newItem = {};
     });
}

When I call this function I add it to my array that I have instantiated, but I cannot access the actual MongoDB even though a 200 response code is returned.

And in my HTML file I have

<form novalidate class="condition-form">
    <fieldset> 
      <input type="number" ng-model="newItem.item_id" name="" placeholder="Enter item id">
      <input type="text" ng-model="newItem.item_name" name="" placeholder="Enter item name">
      <input type="number" ng-model="newItem.item_price" name="" placeholder="Enter item price">
      <input type="submit" ng-click="$ctrl.addNewItem(thing, newItem)" value="Add">
    </fieldset> 
</form>

I'm really at a loss for how I can translate this mongodb call to my MEAN stack application. If it helps I am using Babel with EMCAScript 6. Any help means a lot!

Thanks

share|improve this question

At the backend of it,when the control reaches the things function in API there you will have to use a mongoDB driver(like Mongodb,Mongoose) for interaction with mongo shell. The save function if you are using mongoose will look something like this:

Things.update({'id':req.params.thing._id},{ $push : {items : req.body.items }},function (err,updated) {
if(err){
  console.log(err);
} else {
  output = {'msg':'Updated Successfully'};
}

return res.json(output); });

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.