简体   繁体   中英

How to fetch data from mongodb and show using node.js

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM