0

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

do not consider my Schema. without async is there any way
hello, please could you rephrase your question. I do not understand.
I have updated my answer to reflect your updates, once again. Mongoose does not provide functionality to 'insert multiple collections in a single query'. you can use promise.all to partially achieve this.
0

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.