如何使用nodejs,expressjs从mongodb获取数据

时间:2016-10-09 09:09:35

标签: javascript node.js mongodb express

这是我的代码 文件名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 个答案:

答案 0 :(得分:1)

如果您要使用Mongoose查询现有集合,则应该明确地将该集合的名称传递给模式:

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

如果您不这样做,Mongoose会为您生成一个集合名称,通过降低和复数模型名称(因此模型Student的文档将存储在名为students的集合;请注意尾随-s)。

更多文档here