簡體   English   中英

如何使用 Mongodb Expressjs React js 和 Nodejs 在 2 個不同的 collections 中添加或插入數據?

[英]How to add or insert data in 2 different collections using Mongodb Expressjs React js and Nodejs?

如何使用 MERN 堆棧在 mongodb 中添加或插入具有 2 個不同 collections 的數據?..

很高興看到有人使用 MERN 術語很酷!

所以,讓我們開始你的問題。 當你在節點中使用 mongo 時,最好使用像“Mongoose”之類的 mongo 驅動程序......

在這種情況下,您將准備模型,以便在您的控制器中使用它們。 每個 model 引用一個集合。

最好的方法是調用 mongo 的兩個異步函數,或者只執行兩次保存模式。

例子:

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 - 解決方案二(可行,但我不會這樣做)

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

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()
]);

我總是得到一個 await Promise.All() cuz 的例子,它的運行速度比兩次調用“await”快 2 倍。這肯定是一個很好的做法。

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM