gpt4 book ai didi

javascript - 如何显示书的内容

转载 作者:行者123 更新时间:2023-11-30 14:49:31 25 4
gpt4 key购买 nike

我正在尝试使用 NodeJS、MongoDB 和 Express 创建一本电子书。到目前为止,我只能将所有章节显示为简单列表,如图 1 所示。显然电子书也应该有子章节,所以我希望能够单击第 1 章并查看子章节,如图 2 所示。

我的问题是:如何创建这些子章节?数据库应该怎么看?如何处理所有这些数据?如何正确显示?

附言我已经在 MongoDB 网站上看到了用例,但它对我没有帮助。

代码片段(ebook.js 模型、ebookmain.pug View 、app.js 路由):

模型

const mongoose = require('mongoose')

let Schema = mongoose.Schema

//ebook schema
let ebookSchema = new Schema({
title: String,
body: String
})

// ebook model
let Ebook = mongoose.model('Ebook', ebookSchema)

module.exports = Ebook

查看

extends layout

block content
h1.page-header #{title}
ul.list-group
each ebook, i in ebookpages
li.list-group-item
a.newsLinks(href='/ebookpages/' + ebook._id)= ebook.title

路线

app.get('/ebookmain', (req, res) => 
Ebook.find({}, (err, ebookpages) => {
if (err) {
console.log(err)
} else {
res.render('ebookmain', {title: 'Ebook', ebookpages})
}
}))

图。 1.

enter image description here

图。 2.

enter image description here

已编辑。

如何添加/编辑子章节?

当我有子章节的子章节时怎么办?

添加新章节的代码片段(routes/ebookpages.js):

// add route
router.get('/add', (req, res) =>
res.render('add_ebook', {title: 'Add content'}))
// add submit post route
router.post('/add', (req, res) => {
let ebook = new Ebook()
ebook.title = req.body.title
ebook.body = req.body.body
ebook.save(err => {
if (err) {
console.log(err)
return
} else {
res.redirect('/ebookmain')
}
})
})

最佳答案

let ebookSchema = new Schema({
title: String,
body: String,
subChapters:[{
name: String,
content: String,
}]
});

假设你的收藏中有这样的东西

    [{
_id: '1',
title: 'book 1',
body: '.....',
subChapters[]
},{
_id: '2'
title: book 2'
body: '....',
subChapters: [{
name: 'sub-1',
content: '....'}]

}]

//应用程序.js

const EB = require('./ebook.js');

//Let's say you need to add something to the array i.e subChapters.

var obj = { name: 'sub1', content:'......'};

EB.update({_id: '1'},{ $push: { subChapters: obj } }, function(err, info){
if(err) throw err;
console.log(info);
});

这是您一次只添加一个子章节的情况。

假设您想添加多个子章节,那么您将使用$each 文档:https://docs.mongodb.com/manual/reference/operator/update/push/

使用$pull 从数组文档中删除:https://docs.mongodb.com/manual/reference/operator/update/pull/

要在特定位置插入内容,请检查我的这个答案 https://stackoverflow.com/a/47966974/8380606

希望这对您有所帮助。

关于javascript - 如何显示书的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com