2014-09-19 47 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