![](/img/trans.png)
[英]db.collection.find() returning empty array in node.js but works properly in mongo shell
[英]My node.js GET call returns an empty array from mongo .find()
在這個問題中,我相信我的config.js,model.js和server.js文件是相關的。 誰能解釋為什么這會返回一個郵遞員代碼為200的空數組? 在我的mongo shell中,我可以訪問並查看集合和文件。
這是我嘗試在server.js文件中進行的GET調用。 響應應該是我導入的mongo數據庫中的文件數組。
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 Schema並將其導出的模型文件是:
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之后)和鍵:常量類型值:header中的application / json是:
{
"posts": []
}
問題出在代碼的這一部分:
const BlogPost = mongoose.model('BlogPost', blogPostSchema);
module.exports = {BlogPost};
我在mongoose中使用的數據庫命名為我嘗試過的BlogPost以外的其他名稱,但是mongoose以將集合進行復數和.toLowerCase()-而聞名。 因此,如果我的收藏集是BlogPost,即使在后台使用“ blogposts”也可以使用。
它不應該是localhost:8080 / posts嗎? 您的“獲取”路線上有/ post,而您所說的是/ put。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.