Reputation:
Look I have request in my server.js file
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);
});
});
and my post.js model looks like this:
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);
};
In my eye all code is written right but it does not display data so I double check the mongoDB if i have any record there:
> 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 looks good and contains one record so why when I go to url http://localhost:5000/api/posts
It shows nothing except empty array
[]
Also I do not get any error in cmd/browser.
Gist full code of those 2 files:
server.js: https://gist.github.com/anonymous/9b04527e97e889dcaa109f3ff459a5da
post.js: https://gist.github.com/anonymous/e77064ae71b5ef6d5a9abfd897187ddf
Upvotes: 0
Views: 60
Reputation: 3253
app.get('/api/posts', function (req, res) {
Post.getPosts(function (err, posts) {
res.json(posts);
res.end(); // !!!!!
});
// returns here with no results
});
Please note the res.end()
function that must be called after res.json()
to actually transfer the data.
Upvotes: 0
Reputation: 317
You're not passing in the correct parameters into your getPosts() function. It's expecting callback and limit... I bet it's using 0 as the limit since you're not giving it any.
OR
You could try only having one export. postSchema.getPosts() is where you could attach the method and then just export mongoose.model('Post', postSchema); and nothing else.
Upvotes: 1