【问题标题】:Posting to multiple collections with a single form in AngularJS, NodeJS, MongoDB, Mongoose, and ExpressJS在 AngularJS、NodeJS、MongoDB、Mongoose 和 ExpressJS 中使用单个表单发布到多个集合
【发布时间】:2014-12-01 04:25:25
【问题描述】:

我想要一个表单发布到 mongo 中的两个集合。

HTML 的样子

<form>
   ...Field1
   ...Field2
   ...Field3
   ...Field4
</form>

控制器的外观

app.controller.....

   $scope.var = {$scope.fields}.....
   $http post...
      ...Field 1 & Field 2 to Mongo Collection 1
      ...Field 3 & Field 4 to Mongo Collection 2

基本上不再需要 2 个单独的表单来提供 2 个集合。这可能吗?

提前致谢

追逐

【问题讨论】:

    标签: node.js angularjs mongodb express mongoose


    【解决方案1】:

    这完全取决于您的 HTTP 请求的服务器端处理。假设您定义源数据,例如:

    var composite = {'col1' :{'field1':value, 'field2':value}, 
    'col2' :{'field3':value, 'field4':value}};
    

    你可以编写你的服务器端函数:

    var mongoose = require('mongoose'), Col1 = mongoose.model('Col1'), Col2 = mongoose.model('Col2');
    
    exports.compositeUpdate = function(req, res, next) {
        var template1 = req.body.col1;
        var template2 = req.body.col2;
        // you could also do template1 = new Col1(req.body.col1) and use template1.save()
        var compositeResponse = {};
        Col1.create(template1, function(err, result) {
            // omitting error handling
            compositeResponse.col1 = result;
            Col2.create(template2, function(err, result2) {
                compositeResponse.col2 = result2;
                res.json(compositeResponse);
            });
        });
    };
    

    【讨论】:

    • 这给了我一个很好的视觉来开始编写我的代码。感谢您抽出宝贵时间!
    猜你喜欢
    • 2019-08-07
    • 2021-01-18
    • 2012-11-20
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多