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>
4
  • Use array spread? chapters: [...previousChaptersArray, req.body.chapter] Commented Feb 7, 2018 at 22:45
  • @Li357 I don't quite follow on ...previousChaptersArray. What am I suppose to write there? Commented Feb 7, 2018 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. Commented Feb 7, 2018 at 22:59
  • @AndrewL Meaning I'll override/delete the previous stored chapters if I don't include, lets say, previousChaptersArray? Commented Feb 7, 2018 at 23:06

1 Answer 1

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

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

1 Comment

Worked, thanks. But how can I can I pass a checkbox value? Checked = true, unchecked = false?

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.