[英]How to add values into JSON-array (node.js/mongoose)
I'm using mongoose, adding values from HTML and saving to db with help of mongoose. 我正在使用猫鼬,从HTML添加值,并在猫鼬的帮助下保存到db。 I'm having issue adding value from req.body.chapter
into array from HTML. 我在将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>
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功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.