skip to Main Content

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???

2

Answers


  1. 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

    Login or Signup to reply.
  2. Try with Mongoose hook which will work on create, update, delete of any documents Just take a look on Mongoose hooks you will get the anwser
    Try this link
    https://mongoosejs.com/docs/middleware.html

    Or
    https://medium.com/@justinmanalad/pre-save-hooks-in-mongoose-js-cf1c0959dba2

    May be I’m giving right direction to you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search