[英]How to add or insert data in 2 different collections using Mongodb Expressjs React js and Nodejs?
How to add or insert a data with 2 different collections in mongodb using MERN stack?..如何使用 MERN 堆栈在 mongodb 中添加或插入具有 2 个不同 collections 的数据?..
nice to see someone using the MERN term cool!很高兴看到有人使用 MERN 术语很酷!
So, lets beguin to your question.所以,让我们开始你的问题。 When you're using mongo in node is nice to use a mongo driver like "Mongoose" or like...
当你在节点中使用 mongo 时,最好使用像“Mongoose”之类的 mongo 驱动程序......
In this case you'll prepare your models, to use them in your controllers.在这种情况下,您将准备模型,以便在您的控制器中使用它们。 and each model refer an collection.
每个 model 引用一个集合。
The best way to do it, is calling two async functions of mongo, or just do the save mode twice.最好的方法是调用 mongo 的两个异步函数,或者只执行两次保存模式。
exemples:例子:
1 - Solution one ( and for me the best one ) 1 - 解决方案一(对我来说最好的一个)
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 ) 2 - 解决方案二(可行,但我不会这样做)
const col1 = newCol1Model({data});
const col1 = newCol1Model({data});
col1.save();
col2.save();
2 - Solution tree= ( Maybe Maybe ) 2 - 解决方案树=(也许也许)
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.我总是得到一个 await Promise.All() cuz 的例子,它的运行速度比两次调用“await”快 2 倍。这肯定是一个很好的做法。
Cheers !干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.