2017-04-14 65 views
0
**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 =函數(){

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

請參閱此代碼,幫幫我吧!掙扎數週。有像對象的數組[「名字」:胡蘿蔔,「價格」:24「」:等]

+0

你的問題是這個不是很簡潔,很難理解你在這裏做什麼。如果我理解正確,你想把對象存儲在'items'中,但是你不知道這些項目的確切字段。在這種情況下,將'items'定義爲'items:[]',而不是像'items:[item]'一樣定義。現在你可以在'items'中推動任何對象。 –

回答

0

那些誰卡住參考,而不是使用方法

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! 

});