看我的 server.js 文件中有请求
var Post = require('./../models/post');
//GET ALL POSTS
app.get('/api/posts', function (req, res) {
Post.getPosts(function (err, posts) {
if(err) {
throw err;
}
res.json(posts);
});
});
我的 post.js 模型如下所示:
var mongoose = require('mongoose');
var postSchema = mongoose.Schema({
username: {
type: String,
required: true
},
body: {
type: String,
required: true
},
date: { type: Date,
default: Date.now
}
});
var Post = module.exports = mongoose.model('Post', postSchema);
// Get All Posts
module.exports.getPosts = function (callback, limit) {
Post.find(callback).limit(limit);
};
在我看来,所有代码都写得正确,但它不显示数据,所以我仔细检查 mongoDB 是否有任何记录:
> show dbs
admin 0.000GB
bookstore 0.000GB
local 0.000GB
ownfb 0.000GB
> use ownfb
switched to db ownfb
> show collections
posts
> db.posts.find()
{ "_id" : ObjectId("597aa5b04c08c647b4efb58d"), "type" : "user", "body" : "POST_Z_MONGOOSE_YO" }
MongoDB 看起来不错并且包含一条记录,所以为什么当我转到 url http://localhost:5000/api/posts 时
除了空数组之外什么都没有显示
[]
此外,我在 cmd/浏览器中没有收到任何错误。
Gist 这 2 个文件的完整代码:
服务器.js: https://gist.github.com/anonymous/9b04527e97e889dcaa109f3ff459a5da
post.js: https://gist.github.com/anonymous/e77064ae71b5ef6d5a9abfd897187ddf
最佳答案
您没有将正确的参数传递到 getPosts() 函数中。它正在等待回调和限制...我敢打赌它使用 0 作为限制,因为你没有给它任何限制。
或者
您可以尝试只进行一次导出。 postSchema.getPosts() 是您可以附加方法的地方,然后只需导出 mongoose.model('Post', postSchema);没有别的。
关于javascript - 简单的 Node api请求不显示任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45364371/