Home > database >  Mongoose new document with default new subdocument in other collection bind to parent document
Mongoose new document with default new subdocument in other collection bind to parent document

Time:04-19

There are two collections, Parent and Child. When I create a new document in Parent collection, I want to default create a new document in Child collection and bind the ObjectId of the respective child document to parent document. Is it possible to be done in Mongoose and how???

CodePudding user response:

Mongoose does not provide any such feature by itself, like auto-creation of child documents and linking them, you have to do it manually.

In your case, first, you will need to create the parent document, get the ID from it, then create the child document with the ID of the parent document embedded in it.

And if you want your query to be ACID, you will have to use Mongo transactions, mongoose does support it in versions 5.2 and higher.

What are ACID Transactions? Read this

  • Related