Home > Net >  How to add or insert data in 2 different collections using Mongodb Expressjs React js and Nodejs?
How to add or insert data in 2 different collections using Mongodb Expressjs React js and Nodejs?

Time:03-19

How to add or insert a data with 2 different collections in mongodb using MERN stack?..

CodePudding user response:

To update data across multiple collections within the same database check this https://www.mongodb.com/community/forums/t/update-data-across-multiple-collections-within-the-same-database/118979

CodePudding user response:

nice to see someone using the MERN term cool!

So, lets beguin to your question. When you're using mongo in node is nice to use a mongo driver like "Mongoose" or like...

In this case you'll prepare your models, to use them in your controllers. and each model refer an collection.

The best way to do it, is calling two async functions of mongo, or just do the save mode twice.

exemples:

1 - Solution one ( and for me the best one )

    await Primise.all([
        // using the basic method, but you can use the insert
        // method of your driver, like mongoose
        conn.collection('col1').insert({data}),
        conn.collection('col2').insert({data})
    ]);

2 - Solution two ( it works but i wouldn't do this )

const col1 = newCol1Model({data});
const col1 = newCol1Model({data});
col1.save();
col2.save();

2 - Solution tree= ( Maybe Maybe )

const col1 = newCol1Model({data});
const col1 = newCol1Model({data});
await Primise.all([
   // using the basic method, but you can use the insert
   // method of your driver, like mongoose
   col1.save(),
   col2.save()
]);

I am always getting an exemple of await Promise.All() cuz, this runs 2 times faster than call "await" twice.. and for sure is a good practice.

Cheers !

  • Related