从Angular Controller添加到Mongo中的文档数组

Adding to document array in Mongo from Angular Controller

本文关键字:文档 数组 Mongo Angular Controller 添加      更新时间:2023-09-26

我在从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(输出);});