【问题标题】:how can i add array of objects in schemaless mongoose?如何在无模式猫鼬中添加对象数组?
【发布时间】:2017-09-10 13:40:03
【问题描述】:
**model schema**
var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var item = new Schema({
   name:{type: String, 
   required: true},
   price:{type: String}
 })


 var object=new Schema({
 name:{type: String, 
    required: true},
    items: [item]
});

api.js,发布数据到服务器

router.post('/objectss', function(req, res){ 

  var object= new Object(); **

如何在数组中保存对象数组

**

    object.items.push({firstName: req.body.fname, lastName:      req.body.lname});
    object.name = req.body.name;
        object.save(function (err) {
        if(err) throw err;

        res.json({success: true, message:'allahuakbar'});

    });

// 已保存!

});

angularjs 控制器

$scope.addProduct = function(){

  $scope.items.push({
     fname: $scope.item.fname,
     lname: $scope.item.lname

  });

  $scope.item = {};

}

$scope.submitx = function(inv, item){

        console.log(inv);

        var object = {
      name:inv.name,
      fname:items.fname,
     totalValue:       0
  }
            PostBlog.createInvoice(objects).then(function(data){
          console.log(data);
        });
            $scope.objects= {};
      }

请查看此代码并帮助我!挣扎了几个星期。有一个对象数组,例如 a["name":carrot, "price":24, "":, etc]

【问题讨论】:

  • 你的问题不是很简洁,所以很难理解你在这里想要做什么。如果我理解正确,您想将对象存储在items 中,但您不知道这些项目的确切字段。在这种情况下,将items 定义为items: [],而不是定义为items: [item]。现在您可以将任何对象推入items

标签: angularjs arrays mongodb mongoose


【解决方案1】:

卡住的人参考这个而不是使用方法

 router.post('/invoices', function(req, res){ //by making route in from              


    var invoice = new Invoice();

       for (var i = 0; i < req.body.length; i++) {

 invoice.items.push({name:req.body.fname[i].fname});
  } 
   invoice.name = req.body.name;
    //invoice.items.insertMany(items, function(error, next) {
        invoice.save(function (err) {
        if(err) throw err;

        res.json({success: true, message:'allahuakbar'});

    });



  // saved!

 });

【讨论】:

    猜你喜欢
    • 2017-04-22
    • 1970-01-01
    • 2019-10-30
    • 2019-03-21
    • 2017-12-22
    • 2019-08-21
    • 2018-11-30
    • 2017-11-28
    • 2021-05-31
    相关资源
    最近更新 更多