Javascript My node.js GET调用从mongo.find()返回一个空数组
在这个问题中,我相信我的config.js、model.js和server.js文件是相关的。有人能解释为什么在postman中返回一个代码为200的空数组吗?在我的mongo shell中,我可以访问并查看集合和文件 下面是我试图在server.js文件中进行的GET调用。响应应该是我导入的mongo db中的文件数组Javascript My node.js GET调用从mongo.find()返回一个空数组,javascript,arrays,node.js,mongodb,postman,Javascript,Arrays,Node.js,Mongodb,Postman,在这个问题中,我相信我的config.js、model.js和server.js文件是相关的。有人能解释为什么在postman中返回一个代码为200的空数组吗?在我的mongo shell中,我可以访问并查看集合和文件 下面是我试图在server.js文件中进行的GET调用。响应应该是我导入的mongo db中的文件数组 const {PORT, DATABASE_URL} = require('./config'); const {BlogPost} = require('./models')
const {PORT, DATABASE_URL} = require('./config');
const {BlogPost} = require('./models');
app.get('/posts', (req, res) => {
BlogPost
.find()
.exec()
.then(posts => {
res.json({
posts: posts.map(
(post) => post.apiRepr())
});
})
.catch(
err => {
console.error(err);
res.status(500).json({message: 'Internal server error'});
});
});
正在创建和导出BlogPost架构并将其导出的模型文件是:
const blogPostSchema = mongoose.Schema({
title: {type: String, required: true},
content: {type: String, required: true},
author: {
firstName: {type: String, required: true},
lastName: {type: String, required: true}
}
});
blogPostSchema.virtual('authorString').get(function() {
return `${this.author.firstName} ${this.author.lastName}`.trim()});
blogPostSchema.methods.apiRepr = function() {
return {
id: this._id,
title: this.title,
author: this.authorString,
content: this.content
}
};
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
module.exports = {BlogPost};
通过上面的const{PORT,DATABASE_URL}命令导入的配置文件是:
exports.DATABASE_URL = process.env.DATABASE_URL ||
global.DATABASE_URL ||
'mongodb://localhost/mongoose-blog';
exports.PORT = process.env.PORT || 8080;
最后,我在我的Postman上得到的输出(在输入GET-localhost:8080/post之后)和头中的key:constant-type-value:application/json是:
{
"posts": []
}
应该是本地主机:8080/帖子吗?你的Get路线有/post,你说你的PUTT/post。问题出在代码的这一部分:
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
module.exports = {BlogPost};
我在mongoose中的db命名为BlogPost之外的其他名称,我曾经尝试过BlogPost,但是mongoose以集合的复数化和.toLowerCase()而闻名。因此,如果我的集合是BlogPost,它会工作,即使在幕后它会使用“blogposts”。。然后(posts=>{res.json({posts:posts.map((post)=>post.apiRepr())};})我认为这部分代码有问题。在这里尝试console.log()并检查谢谢,我做到了。控制台日志(posts);也给了我一个空数组[]不,只是因为这是一个博客应用程序,所以有点混乱。所以我把所有的帖子都放到了博客上。