从Angular Controller添加到Mongo中的文档数组
Adding to document array in Mongo from Angular Controller
我在从Angular Controller向MongoDB中的JSON对象数组中插入一个新的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构建了我的应用程序,现在更感兴趣的是获得一个功能原型。在我的角度控制器中,我使用这个功能
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堆栈应用程序。如果有帮助的话,我会将Babel与EMCAScript 6一起使用。任何帮助都意义重大!
感谢
在它的后端,当控件到达API中的things函数时,您将不得不使用mongoDB驱动程序(如mongoDB、Mongoose)与mongoshell进行交互。如果你使用猫鼬,保存功能会看起来像这样:
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'};
}
返回res.json(输出);});
相关文章:
- 返回一个关联数组,而不是mongoose中的文档数组
- 如何获取文档数组中元素的计数-MongoDB
- MongoDB findAndModify:>>>查找和更新文档数组中的对象
- 如何在猫鼬.js子文档数组中定义实例方法
- 通过node-js脚本将文档数组插入mongodb中的数据库时出现问题
- 通过 Meteor / Mongo 返回子文档数组
- Meteor:更新文档数组中的嵌套对象
- 通过Javascript中的JSON文档数组&使用KnockoutJS的JQuery
- 如何使用另一个文档数组中的id对光标进行排序
- 将字段插入子文档数组中.意外行为
- 如何从JSON文档数组中提取字段数组
- 如何在Mongodb中返回符合给定条件的子文档数组
- 按筛选的子文档数组元素计数排序
- 将新条目推入mongoDB文档数组
- Meteor AutoForm:如何用子文档数组更新模式值
- 我如何将文档数组更改为MongoDB shell中的值数组
- Mongodb:聚合子文档数组的值
- IBM worklight JSON存储删除文档数组
- 循环一个嵌入文档数组,将新值推入一个字段
- 插入到MongoDB文档数组的前面,没有$position和$each