'How to Insert documents to multiple collection in a single query using nodejs
I am trying to insert documents into multiple collections by writing single query.
Let consider that I have two collections person
and address
. I want insert documents to both of this collections in single query. That is documents which are like fname,lname should be inserted inside pesron
collection and documents which are like city,state,country should be inserted to address
collections.
Is there any I can make this happen, If it is possible providing any answer with example will be appreciated.
Solution 1:[1]
mongoose doesn't provide this functionality & also node.js is synchronous... so you cant do 2 things at the same time. Is suggest leveraging Promise.all
(async () => {
const [createdPerson, createdAddress] = await Promise.all([
person.create({
fname: "name",
lname: "lname"
}),
address.create({
city: "city",
state: "state",
country: "country"
})
]);
})();
Solution 2:[2]
I believe this is possible using MongoDb Transactions. I haven't tested yet, but there's a good example here, and you can view it's settings here. Hope it helps!
Solution 3:[3]
If you want to use two dependent documents in two different collections so that if one insert fails other should fail also then you need to use MongoDB transactions API.
MongoDB transactions - https://www.mongodb.com/docs/manual/core/transactions/ Mongoose reference to transactions - https://mongoosejs.com/docs/transactions.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Iglesias Leonardo |
Solution 3 | shubham |