如何将值添加到JSON数组中(node.js / mongoose)

时间:2018-02-07 22:41:35

标签: javascript node.js mongodb mongoose

我使用mongoose,在HTML中添加值并借助mongoose保存到db。我有问题从req.body.chapter向HTML添加数值。

路线:

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

预订模型:

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>

1 个答案:

答案 0 :(得分:0)

因此,如果数据如下所示,您可以将其放入:

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

路线:

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

如果您只想将章节添加到现有数据中,请查看Using Mongoose / MongoDB $addToSet functionality on array of objects