I'm currently facing a challenge when it comes to inserting a new JSON object into an array of JSON objects in MongoDB from my Angular Controller.
To simplify, let's consider this schema:
var ItemSchema = new mongoose.Schema({
id: Number,
items: [{
item_id: Number,
item_name: String,
item_price: Number
}]
});
Inserting data into MongoDB using the Mongo console can be achieved with:
db.items.update(
{ "_id": ObjectId("579b7860b168c80c1fe8a32a")},
{ $push: {
"items": {
"item_id" : 134,
"item_name" : "sampleItem",
"item_price" : 234.00
}}
})
Yet, translating this process into an http request in AngularJS is where I'm encountering difficulties. I utilized Yeoman for scaffolding and am primarily focused on creating a functional prototype at the moment. In my Angular Controller, the function being used is:
addNewItem(item, newItem) {
this.$http.put('/api/items/' + item._id, { 'items': newItem})
// upon success, clear the fields
.then( response => {
console.log(response);
alert(this.newItem);
item.items.push(newItem);
newItem = {};
});
}
Although invoking this function successfully adds the new item to my instantiated array, I'm unable to access MongoDB even though a 200 response code is returned.
In the HTML file, the following form structure exists:
<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(item, newItem)" value="Add">
</fieldset>
</form>
Deciphering how to integrate this mongodb call into my MEAN stack application has become quite perplexing. For additional context, Babel is being used alongside EMCAScript 6. Any assistance would be greatly appreciated!
Thank you