Tufail Qurashe Tufail Qurashe - 2 months ago 7
Node.js Question

How to fetch data from mongodb using nodejs, expressjs

Here is my code
file name student.js


var mongoose = require('mongoose');

var studentSchema = new mongoose.Schema({

name:{
type: String,
required: true
},
rollno:{
type: Number,
required: true
},
grade:{
type: String,
required: true
},
result:{
type: String,
required: true
}
});


var Student = module.exports = mongoose.model('Student',studentSchema);


module.exports.getStudents = function (callback){

Student.find(callback);
}

**filename app.js**

var express = require('express');

var app = express();

var mongoose = require('mongoose');

var PORT= process.env.PORT || 3000;


Student = require('./models/student');


mongoose.connect('mongodb://localhost/register');

var db= mongoose.connection;

app.get('/api/student', function (req,res){

Student.getStudents(function (err, student){
if(err){
throw err;
}
res.json(student);
});
});


app.listen(PORT);

console.log('Running app on port:' + PORT);

Answer

If you have an existing collection that you want to query using Mongoose, you should pass the name of that collection to the schema explicitly:

var studentSchema = new mongoose.Schema({ ... }, { collection : 'student' });

If you don't, Mongoose will generate a collection name for you, by lowercasing and pluralizing the model name (so documents for the model Student will be stored in the collection called students; notice the trailing -s).

More documentation here.