0

I'm using mongoose, adding values from HTML and saving to db with help of mongoose. I'm having issue adding value from req.body.chapter into array from HTML.

Route:

  const newBook = {
      book: req.body.book,
      summary: req.body.summary,
      chapters: //how to add value into chapter-array?
    }

Book-model:

const BookSchema = new Schema({
 Title: {
    type: String,
    required: true
  },
  Summary: {
    type: String,
    required: true
  },
  chapters : [{
    chapter: {
      type: String,
      required: true
  }]   
});

HTML:

<div class="form-group">
      <label for="book">Title:</label>
      <input type="text" class="form-control" name="book" required>
</div>
<div class="form-group">
      <label for="Summary">Summary:</label>
      <input type="text" class="form-control" name="Summary" required>
</div>
<div class="form-group">
      <label for="chapter">chapter:</label>
      <input type="text" class="form-control" name="chapter" required>
</div>
ipid
  • 253
  • 1
  • 4
  • 16
  • Use array spread? `chapters: [...previousChaptersArray, req.body.chapter]` – Andrew Li Feb 07 '18 at 22:45
  • @Li357 I don't quite follow on `...previousChaptersArray`. What am I suppose to write there? – ipid Feb 07 '18 at 22:51
  • That is if you want to include previous chapters that you had stored as a variable. Such as you looked up the book, and you are adding chapters. It is better to an "addToSet" if you are just updating, because it stops issues if 2 people are updating it at once. – AndrewL Feb 07 '18 at 22:59
  • @AndrewL Meaning I'll override/delete the previous stored chapters if I don't include, lets say, `previousChaptersArray`? – ipid Feb 07 '18 at 23:06

1 Answers1

0

So if the data looks like this, you can just put it in:

req.body.chapters = ["1", "3"];

Route:

const newBook = {
   book: req.body.book,
   summary: req.body.summary,
   chapters: req.body.chapters
 }

If you just want to add the chapters to existing data, then have a look at Using Mongoose / MongoDB $addToSet functionality on array of objects

AndrewL
  • 334
  • 2
  • 13
  • Worked, thanks. But how can I can I pass a checkbox value? Checked = true, unchecked = false? – ipid Feb 07 '18 at 23:34