Chase Nelson Chase Nelson - 2 years ago 134
AngularJS Question

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


What the controller would look like


$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


Answer Source

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
    var compositeResponse = {};
    Col1.create(template1, function(err, result) {
        // omitting error handling
        compositeResponse.col1 = result;
        Col2.create(template2, function(err, result2) {
            compositeResponse.col2 = result2;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download