【问题标题】:Save two referenced documents simultaneously同时保存两个参考文档
【发布时间】:2014-11-13 12:00:31
【问题描述】:

我有一个库存应用程序,我想在其中设置有关库存的一些详细信息,然后插入库存的所有项目。我想在两个不同的集合中插入库存详细信息和项目,以便过滤项目。我正在使用 MEAN Stack,我在其中修改了 crud 模块以接受一些额外的字段,并制作了用于填充 items 数组的 UI。这是我到目前为止所拥有的:

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?

【问题讨论】:

    标签: node.js angularjs mongodb mongoose meanjs


    【解决方案1】:

    通过说“同时”,我认为您需要事务功能,这实际上是 RDBMS 的事情,MongoDB 不支持。如果您的应用程序强烈依赖这些特性,恐怕 MongoDB 不是您的正确选择。

    回到你的问题,我不明白为什么你必须将stockstock item 存储在两个不同的集合中。将它们存储在一个集合中将是更好的选择。更多信息可以参考 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
    ]);
    

    【讨论】:

    • 这样我就可以使用非规范化数据模型并将 stockItems 嵌入到 Stocks 中。但是使用这个模型,我可以从所有股票中查询所有红色的 stockItems 吗?
    • @FacuFerrari 是的,我的意思是你可以将库存项目存储在嵌入文档中,这样当你保存它们时它就是原子的。我真的不知道您将如何查询“red stockItems”。您是否还有其他商品库存集合,并且每条记录代表特定商品的库存?
    猜你喜欢
    • 2015-08-18
    • 2013-05-18
    • 2015-10-10
    • 2019-07-14
    • 2019-12-05
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多