2014-09-19 46 views
0

我有一個股票應用程序,我想設置有關股票的一些細節,然後插入股票的所有項目。我想在兩個不同的集合中插入庫存細節和項目,然後我可以過濾這些項目。我使用的平均堆棧,我已經修改了污物模塊接受一些額外的領域,也取得了填充的項目的UI array.This是我到目前爲止有:同時保存兩個參考文檔

scope.stockItems = []; 

    $scope.createStockItem = function() { 
     $scope.stockItems.push(
      { 
       brand: $scope.brand, 
       style: $scope.style, 
       amount: $scope.amount 
      } 
     ); 

     $scope.brand = false; 
     $scope.style = false; 
     $scope.amount = ''; 
    }; 

    // Create new Stock 
    $scope.create = function() { 
     // Create new Stock object 
     var stock = new Stocks ({ 
      name: this.name, 
      details: this.details, 
      stockDate: this.stockDate 
     }); 

     // Redirect after save 
     stock.$save(function(response) { 
      $location.path('stocks/' + response._id); 

      // Clear form fields 
      $scope.name = ''; 
     }, function(errorResponse) { 
      $scope.error = errorResponse.data.message; 
     }); 
    }; 

股票模型:

var StockSchema = new Schema({ 
name: { 
    type: String, 
    default: '', 
    required: 'Please fill Stock name', 
    trim: true 
}, 
details: { 
    type: String, 
    default: '', 
    required: 'Please fill Stock details' 
}, 
stockDate: Date 
created: { 
    type: Date, 
    default: Date.now 
}, 
user: { 
    type: Schema.ObjectId, 
    ref: 'User' 
} 
}); 

,並在服務器控制器的方法:

exports.create = function(req, res) { 
var stock = new Stock(req.body); 

stock.user = req.user; 

stock.save(function(err) { 
    if (err) { 
     return res.status(400).send({ 
      message: errorHandler.getErrorMessage(err) 
     }); 
    } else { 
     res.jsonp(stock); 
    } 
}); 
}; 

如何發送到請求並保存stockItems也?

回答

0

通過說'同時'我認爲你需要交易功能,這實際上是一個RDBMS的事情,並且不被MongoDB支持。如果您的應用程序強烈依賴這些功能,恐怕MongoDB不適合您。

所以回到你的問題,我不明白爲什麼你必須存儲stockstock item在2個不同的集合。將它們存儲在一個集合中將是更好的選擇。有關更多信息,請參閱MongoDB手冊的Data Model Design。如果只是爲了過濾所有庫存物品,aggregation framework就是爲此目的而設計的。以及Map/Reduce。這裏聚合框架更適合您的問題。你會有這樣的事情:

db.stock.aggregate([ 
    {$match: {...}}, // same as find criteria. to narrow down data range 
    {$unwind: "$items"}, // unwind items. 
    ... // probably some other $match to filter the items 
]); 
+0

所以你我可以使用非規範化的數據模型,並在stocks中嵌入stockItems。但是使用這個模型可以查詢所有股票中的所有紅股票嗎? – 2014-09-19 09:49:35

+0

@FacuFerrari是的我的意思是你可以將庫存物品存儲在嵌入式文檔中,這樣當你保存它們時它就是原子。我真的不知道你將如何去查詢'紅股'。你是否有另外一批物品庫存,每個記錄代表一個特定物品的庫存? – yaoxing 2014-09-21 07:15:16