简体   繁体   中英

Posting to multiple collections with a single form in AngularJS, NodeJS, MongoDB, Mongoose, and ExpressJS

I want a single form to post to two collections in mongo.

What the HTML would look like

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

What the controller would look like

app.controller.....

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

Essentially removing the need for 2 seperate forms to feed 2 collections. Is this possible?

Thanks in advance

Chase

This is entirely dependent on the server-side processing of your HTTP request. Supposing you define source data like :

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

You could write your server-side function :

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);
        });
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM