Save in several collections Mongoose same call

0

I need to save the information of my Arrays [data_inver], [asociar_inver] in Mongoosee at the same time in a same method of my API.

Right now I am launching these two methods:

// save multiple documents to the collection referenced by Data_Greenhouse Model
    data_Greenhouse.collection.insert(data_inver, function (err, docs) {
      if (err){
        res.status(500).send({message: 'Error al guardar en la base de datos'})
      } else {
        console.log("Multiple documents inserted to Collection");
        res.status(200).send({data_Greenhouse: docs})

      }
    });

    // save multiple documents to the collection referenced by asociar_Greenhouse Model
    asociar_Greenhouse.collection.insert(asociar_inver, function (err, docs) {
      if (err){
        res.status(500).send({message: 'Error al guardar en la base de datos'})
      } else {
        console.log("Multiple documents inserted to Collection");
        res.status(200).send({asociar_Greenhouse: docs})

      }
    });

The problem I have is that I do not know how to tell you to save in different collections with a single call, since the error is given to me by throwing the two one after the other, since it gives an error in the headers because the request It was already sent.

Is it possible to save multiple documents in different collections in the same mongo call?

All this I'm doing about NodeJS.

Thanks greetings.

    
asked by Manolait 24.04.2018 в 13:27
source

1 answer

0

You can use the library async , specifically the method parallel which will help you execute the 2 inserts. Once the two have been executed, you would have a callback with possible errors or results of the inserts.

Ex:

async.parallel([
    function(callback) {
        setTimeout(function() {
            callback(null, 'one');
        }, 200);
    },
    function(callback) {
        setTimeout(function() {
            callback(null, 'two');
        }, 100);
    }
],
// optional callback
function(err, results) {
    // the results array will equal ['one','two'] even though
    // the second function had a shorter timeout.
});

// an example using an object instead of an array
async.parallel({
    one: function(callback) {
        setTimeout(function() {
            callback(null, 1);
        }, 200);
    },
    two: function(callback) {
        setTimeout(function() {
            callback(null, 2);
        }, 100);
    }
}, function(err, results) {
    // results is now equals to: {one: 1, two: 2}
});
    
answered by 03.05.2018 в 19:50