拜托,我是一个初学者,我正在尝试使用 Node 运行一个博客网站...我一直在尝试编写代码以使用 nodejs、express、ejs 和 mongoose 从我的 MongoDB 数据库获取数据到我的前端但一切都无济于事,请我帮助。
这是我的app.js
//app.js
const express = require('express'); const ejs = require('ejs'); const mongoose = require('mongoose'); const path = require('path'); const { type } = require('os');
const port = 3000 const app = express();
// const image = require('./public/image')
app.use(express.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views')) app.set('view engine ', 'ejs'); app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static('public')); // dotenv.config();
mongoose.connect('mongodb://localhost:27017/blog')your text const db = mongoose.connection db.once('open', ()=>{ console.log("Monogdb connected") })
const postSchema = new mongoose.Schema({ title: { type: String, required: true, },
body: { type: String, required: true, }, }); const datas = mongoose.model("datas", postSchema);
app.post('/post', async (req, res) =>{ const {title,body} = req.body const user = new datas ({ title, body }) await user.save() console.log(user) res.redirect("/new.ejs") });
app.get('/', async (req, res) => { res.render('index.ejs') // res.render('index.ejs', {posts: posts}); });
app.get('/new.ejs', async (req, res) => { res.render('new.ejs'); }); app.get('/faqs.ejs', async (req, res) => { res.render('faqs.ejs'); }); app.get('/team.ejs', async (req, res) => { res.render('team.ejs'); });
app.listen(port, () => { console.log("Server started"); });
Here, new.ejs {for adding posts}
<form class="gru" action="/post" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title" autofocus required><br><br>
</div>
<div class="form-group">
<textarea class="form-control" name="body" id="body" placeholder="Your Content" rows="3" autofocus required></textarea>
</div><br>
<input class="sticky" type="file" name="image" accept="image/*" style="margin-left: 120px;"><br><br>
<button type="submit" onclick="showAlert()">Publish</button>
</form>
要使用 mongoose 从 mongodb 数据库检索数据,可以使用 `find(),如下面的代码:
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
您还可以使用 mongoose 文档:https://mongoosejs.com/docs/guide.html