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

时间:2021-12-17 06:53:02

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.

我正在使用mongoose,从HTML添加值并在mongoose的帮助下保存到db。我有问题从req.body.chapter将值添加到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:

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 个解决方案

#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

如果您只想将章节添加到现有数据,那么请查看在对象数组上使用Mongoose / MongoDB $ addToSet功能

#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

如果您只想将章节添加到现有数据,那么请查看在对象数组上使用Mongoose / MongoDB $ addToSet功能