0

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

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.