【发布时间】:2016-08-02 14:19:20
【问题描述】:
我在从 Angular 控制器将新 JSON 对象插入 MongoDB 中的 JSON 对象数组时遇到问题。
我正在尝试做的一个简单概念是针对此架构:
var ThingSchema = new mongoose.Schema({
id: Number,
items: [{
item_id: Number,
item_name: String,
item_price: Number
}]
});
并将其添加到我可以使用的 Mongo 控制台中的 mongodb:
db.things.update(
{ "_id": ObjectId("579b7860b168c80c1fe8a32a")},
{ $push: {
"items": {
"item_id" : 134,
"item_name" : "sampleItem",
"item_price" : 234.00
}}
})
但是,我不确定如何将其转换为来自 AngularJS 的 http 请求。我使用 Yeoman 搭建了我的应用程序,并且现在对获得功能原型更感兴趣。在我的 Angular 控制器中,我正在使用此功能
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 = {};
});
}
当我调用这个函数时,我将它添加到我已实例化的数组中,但即使返回 200 响应代码,我也无法访问实际的 MongoDB。
在我的 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 堆栈应用程序。如果它有帮助,我正在使用带有 EMCAScript 6 的 Babel。任何帮助都意义重大!
谢谢
【问题讨论】:
标签: javascript angularjs json mongodb mean-stack