【发布时间】:2018-11-04 16:33:46
【问题描述】:
我认为这与我定义架构的方式有关,但我似乎无法找到错误所在...我有一个几乎相同的文件设置,它运行良好,但很遗憾我没有能够在任何地方找到此问题的副本。
当通过 Postman 向我的本地 Express 实例发送 API 请求时,只有“标题”请求正文值存储在数据库中。我将以下简单请求作为 Application/Json 发送到我的路由(认为使用 x-www-form-urlencoded 时也会发生同样的情况):
{
"postTitle": "title goes here",
"postContent": "body goes here",
"isPublished": true
}
这显然是在express中注册的,好像我记录了我可以看到这些数据的对象(加上时间戳和一个_id):
{ _id: 5b07d9c0b8124e0599079c04,
postTitle: 'title goes here',
postContent: 'body goes here',
isPublished: true,
createdAt: 2018-05-25T09:39:12.869Z,
updatedAt: 2018-05-25T09:39:12.869Z,
__v: 0 }
但是,当我使用对象的 ID 向我的路由发送 get 请求时,我会收到以下响应:
{ "_id": "5b07d9c0b8124e0599079c04" }
同样,如果我发送列出所有对象的请求,我会收到以下响应:
{
"posts": [
{
"_id": "5b07d9c0b8124e0599079c04"
},
{
"_id": "5b07d9c0b8124e0599079c03"
},
{
"_id": "5b07d9914f10ce058f137eba"
}
]
}
奇怪的是,有时作为响应的一部分发送的帖子标题包含在响应中,有时则不包含。
我的架构如下:
var postSchema = new Schema({
postTitle: String,
postContent: String,
isPublished: Boolean
},
{
timestamps: true
});
我的 POST 请求的 post API 路由如下:
router.post('/posts', (req, res, next) => {
var postTitle = req.body.postTitle;
var postContent = req.body.postContent;
var isPublished = req.body.isPublished;
var newPost = new Post({
postTitle: postTitle,
postContent: postContent,
isPublished: isPublished
});
newPost.save(function (error) {
if (error) {
console.log(error)
}
res.send({
success: true,
message: 'Post saved successfully!'
})
})
});
(如果您不使用路由器,您将使用 'app.post' 而不是 'router.post')再次,这有点冗长,但一切正常。
我的GET路线如下:
router.get('/posts', (req, res) => {
Post.find({}, 'title content published', function (error, posts) {
if (error) { console.error(error); }
res.send({
posts: posts
})
}).sort({_id:-1})
});
【问题讨论】:
-
虽然这很好,但 Stack Overflow 用于“问题”和“答案”。您应该将“问题”与“答案”分开,而不仅仅是问题中的“博客”内容。发布您自己的答案很好,但这里的格式是“答案”是预期的。这都写在“问题”中了。
-
注意,谢谢。如果我在发布问题后找到了解决方案,我会这样做,但我在输入问题的过程中发现了它。我已对其进行了重新格式化,使其不像博客那样,以便可以将问题标记为已回答。
-
也许从“找到解决方案”中编辑其余部分,因为您现在已经添加了该位作为答案。
-
是的,我已经这样做了。我先添加了评论,这样我就可以更轻松地复制/粘贴相关内容,然后再将其从主帖中删除。我想在问题中包含我的错误,以明确指出问题所在。
标签: javascript api express mongoose missing-data