2016-08-02 66 views
0

我在從Angular Controller中將新的JSON對象插入到MongoDB中的JSON對象數組時遇到問題。從Angular Controller添加到Mongo中的文檔數組

的什麼,我試圖做一個簡單的概念是這樣的模式:

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

並把它添加到我的蒙戈控制檯MongoDB中,我可以使用:

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

然而,我不知道如何將它轉換爲來自AngularJS的http請求。我用Yeoman來支撐我的應用程序,現在更感興趣的是獲取功能原型。在我的角度控制,我使用這個功能

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

當我把這個功能我把它添加到我的數組,我實例化,但我不能訪問實際的MongoDB即使返回200響應代碼。

而在我的HTML文件我有

<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> 

我真的在爲我怎麼能翻譯這MongoDB的打到我MEAN堆棧應用的損失。如果這有助於我使用Babel和EMCAScript 6.任何幫助都意味着很多!

感謝

回答

0

在它的後端,當控制達到API的事情函數然後您就可以使用MongoDB的驅動程序(如MongoDB中,貓鼬),用於與蒙戈外殼的相互作用。如果您使用貓鼬,保存功能如下所示:

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

相關問題