How to fetch data from mongodb using nodejs, expressjs

让人想犯罪 __ 提交于 2021-01-29 07:50:24

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/39941870/how-to-fetch-data-from-mongodb-using-nodejs-expressjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!