Express/Mongoose数据返回异常求助:POST完整GET仅得_id
问题根源:字段名不匹配导致的投影错误
嘿,我一眼就揪出你遇到的问题啦!核心原因是你的GET请求路由里的投影字段和Schema定义的字段名完全不匹配,这才导致返回结果只有_id。
具体分析
你的Schema定义的字段是:postTitle、postContent、isPublished,还加上了自动生成的createdAt和updatedAt。但在获取所有文章的GET路由里,你写的是:
Post.find({}, 'title content published', function (error, posts) { ... })
这里的title、content、published根本不是你Schema里的字段名,MongoDB找不到这些字段,就只会默认返回_id(这是MongoDB的默认行为,除非你明确用-_id排除它)。至于偶尔能看到标题,大概率是你某次测试时不小心用对了字段名,或者有缓存干扰。
修复方案
把投影字段改成和Schema一致的名称就行,有两种写法:
写法1:字符串形式(注意空格分隔字段)
router.get('/posts', (req, res) => { Post.find({}, 'postTitle postContent isPublished createdAt updatedAt', function (error, posts) { if (error) { console.error(error); } res.send({ posts: posts }) }).sort({_id:-1}) });
写法2:对象形式(更清晰,不容易写错)
router.get('/posts', (req, res) => { Post.find({}, { postTitle: 1, postContent: 1, isPublished: 1, createdAt: 1, updatedAt: 1 }, function (error, posts) { if (error) { console.error(error); } res.send({ posts: posts }) }).sort({_id:-1}) });
如果你想返回文档里的所有字段,其实更简单,直接省略第二个投影参数就行:
router.get('/posts', (req, res) => { Post.find({}, function (error, posts) { if (error) { console.error(error); } res.send({ posts: posts }) }).sort({_id:-1}) });
验证
修改完路由后,再发送GET请求,就能看到包含所有字段的完整文章数据啦,和你存入数据库时的结构一致。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

