3

I have a database on mlab and now I was starting a new Project and trying to simply get data from there.

The Database has only one collection called Article.

On my Node js project, using Mongoose, I created the Model for it:

var mongoose = require('mongoose');

var articleSchema = new mongoose.Schema({
  title: { type: String, required: true },
  body: { type: String }
});

var Article = mongoose.model('Article', articleSchema);

module.exports = Article;

The in my controller I just did this:

Article.find({}, function (err, articles) {
    res.send(articles);
});

I should receive more than 300 articles but the response is just an empty Array.

I was wondering if I need to run a few more command in order to connect to the db correctly, but I don't know it...

3
  • 1
    you have var Article = mongoose.model('Article', articleSchema);, but you define article, not articleSchema, one line above. Can this be the issue? Commented May 3, 2016 at 14:19
  • 1
    @TudorConstantin thanks for your hint, I just checked and I misstyped here in Stackoverflow... I just edited the question. Commented May 3, 2016 at 14:21
  • Do you get any errors while connecting (code not presented)? Maybe you are connecting to a different uri and therefore the articles collection is empty? Commented May 3, 2016 at 15:39

1 Answer 1

5

If you want to fetch on an existing Article collection:

var articleSchema = new mongoose.Schema({
  title: { type: String, required: true },
  body: { type: String }
}, { collection : 'Article' });
Sign up to request clarification or add additional context in comments.

4 Comments

This is just a more complicated version of the very same code. I don't know how this answers any problem?
No I think { collection : 'Article' } solves the problem.
Yes, it was enough to write to add { collection : 'Article' } to answer my question, it should be better to edit the answer to better fit the question. Thanks.
Oh now I get it. Good catch Thomi! You just should've answered it straightly that there's a typo/difference in the collection name, rather than writing code for separate files. Anyways, good work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.