我让dDeepsickck写了个东西,随便弄来玩的

4 叮当猫 2天前 118次点击

简易论坛

+

帖子详情

// server.js

const express = require('express');

const mongoose = require('mongoose');

const app = express();

app.use(express.json());

// 连接 MongoDB

mongoose.connect('mongodb://localhost/forum', { useNewUrlParser: true });

// 定义数据模型

const PostSchema = new mongoose.Schema({

title: String,

content: String,

comments: [{

content: String,

createdAt: { type: Date, default: Date.now }

}],

createdAt: { type: Date, default: Date.now }

});

const Post = mongoose.model('Post', PostSchema);

// 接口路由

app.get('/posts', async (req, res) => {

const posts = await Post.find().sort({ createdAt: -1 });

res.json(posts);

});

app.post('/posts', async (req, res) => {

const post = new Post(req.body);

await post.save();

res.status(201).json(post);

});

app.get('/posts/:id', async (req, res) => {

const post = await Post.findById(req.params.id);

res.json(post);

});

app.post('/posts/:id/comments', async (req, res) => {

const post = await Post.findById(req.params.id);

post.comments.push(req.body);

await post.save();

res.status(201).json(post);

});

app.listen(3000, () => console.log('Server running on port 3000'));

目前还没有评论
添加一条新评论

登录后可以发表评论 去登录