How to insert multiple documents into sub document at once in mongoose

Viewed 788

I created a collection which has a sub-document of array like this below:

const ChapterSchema = new Schema({
    intro: { type: String },
    topics: { type: [TopicSchema] }
},

I want to add multiple topics in topics sub-document of Chapter. I can insert a single topic by this code below:

ChapterSchema.update(
  {_id: /* doc id */ },
  {$push: {'topics.$': { /* single topic object */ }},
  callback
)

But, I want to insert a topic array to the above sub-documents. How could I able to do that?

1 Answers

$push offers a special syntax with $each:

ChapterSchema.update(
    { _id: /* doc id */ },
    { $push: {'topics': { $each: /* array of topics */ }},
    callback
)
Related