gpt4 book ai didi

javascript - Mongoose 模型 key 未插入 Postman 发布请求中

转载 作者:行者123 更新时间:2023-12-03 02:32:34 25 4
gpt4 key购买 nike

我正在尝试使用下面的 post 方法来创建新文档。但是,当我在 Postman 中发送发布请求(例如 http://localhost:3000/api/posts?title=HeaderThree )时,会创建一个新文档,但缺少键和值。

router.route('/posts')
.get(function(req, res) {
Post.find(function(err, posts) {
if (err) { return res.send(err)}
res.json(posts)
})
})
.post(function(req, res) {
const post = new Post(
{
title: req.body.title,
text: req.body.text
}
);

post.save(function(err, post) {
if (err) { return res.send(err)};
res.json({ message: 'Post added!'});
});
});

架构是这样的:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const PostSchema = new Schema(
{
date: {type: Date, default: Date.now},
title: {type: String},
text: {type: String },
comments: {type: Array}
}
)

module.exports = mongoose.model('PostSchema', PostSchema);

最佳答案

如果您将数据作为查询字符串发送:

 http://localhost:3000/api/posts?title=HeaderThree
^^^^^^^^^^^^^^^^^

然后你必须使用req.query从express服务器获取它们:

const post = new Post(
{
title: req.query.title,
text: req.query.text
}
);

如果您想将数据作为表单正文发送,则需要使用body-parser中间件:

const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

...

现在您可以使用req.body对象来获取提交的数据。

最后一件事,不要忘记在 postman 的正文选项卡下填充表单数据

关于javascript - Mongoose 模型 key 未插入 Postman 发布请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672846/

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