John
John

Reputation: 1095

My node.js GET call returns an empty array from mongo .find()

In this question I believe my config.js, model.js, and server.js file are relevant. Can anyone explain why this is returning an empty array with a code of 200 in postman? In my mongo shell I can access and see the collection and files.

Here is the GET call I am trying to make in the server.js file. The response should be an array of my files from a mongo db I imported.

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'});
    });
});

My model file that is creating and exporting the BlogPost Schema and exporting it is:

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};

The config file that is being imported byt the const{PORT, DATABASE_URL} command above is:

exports.DATABASE_URL = process.env.DATABASE_URL ||
                       global.DATABASE_URL ||
                      'mongodb://localhost/mongoose-blog';

exports.PORT = process.env.PORT || 8080;

And finally, the output I am getting on my Postman (after putting in GET localhost:8080 /post) and key: constant-type value: application/json in my header is:

{
  "posts": []
}

Upvotes: 0

Views: 1053

Answers (2)

John
John

Reputation: 1095

The problem was in this part of the code:

const BlogPost = mongoose.model('BlogPost', blogPostSchema);
module.exports = {BlogPost};

My db in mongoose was named something other than BlogPost, which I had tried, however mongoose is known for pluralizing and .toLowerCase()-ing the collections. So therefore if my collection was BlogPost, it would have worked even though behind the scenes it would have been using "blogposts".

Upvotes: 1

mrtaz
mrtaz

Reputation: 444

Shouldnt it be localhost:8080/posts ? Your Get route has /posts and your saying your putting /post.

Upvotes: 0

Related Questions