1

Following is my code to fetch data from a collection and show it on index page, but it is not giving the results.

Node Code-

var app = require('express')();
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/test';

mongoose.connect(dbURI);
var testSchema = new mongoose.Schema({
        name: String,
        rollnum: String
});

var Test = mongoose.model('Test', testSchema);

app.get('/', function(req, res){
        Test.find({},function(err, docs){
                res.send('index',{docs:docs});
        });
        //res.send('test');
});

app.listen(3001);

However I check and have a collection in db like this -

Query fire - db.testinfo.find()

Output -

{
"_id": ObjectId("123456..78"),
"name": "test",
"rollnum": "XXXX"
}

After hitting the URL - http://127.0.0.1:3001/

This is the output I am getting -

{
  "docs": []
}

However I was expecting to get the result of name, rollnum.

Please let me know what I am doing wrong.

1 Answer 1

3

When you register a model in Mongoose, it uses the pluralized, lower-cased model name as the name of the collection it's tied to. So because your model name is Test, the collection name is tests.

To tie the model to testinfo instead, pass that name as the third parameter to your model call:

var Test = mongoose.model('Test', testSchema, 'testinfo');
Sign up to request clarification or add additional context in comments.

2 Comments

wow that works..sorry for the late response..was taking the meal :)
just for my knowledge..can you please refer any good link or book to follow for node+mongoose where I can easily understand the CRUD concepts for node+mongo beginner as I searched over the internet and everone is following thr own conventions so I am lost being a beginner

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.