![](/img/trans.png)
[英]How can do POST data using API from REACTJS ,NODEJS,EXPRESSJS AND MONGODB?
[英]How to fetch data from mongodb using nodejs, expressjs
這是我的代碼文件名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);
如果您有要使用Mongoose查詢的現有集合,則應將該集合的名稱明確傳遞給架構:
var studentSchema = new mongoose.Schema({ ... }, { collection : 'student' });
如果您不這樣做,Mongoose將通過簡化模型名稱並將其復數形式為您生成一個集合名稱(因此模型Student
文檔將存儲在名為students
的集合中;請注意-s
)。
更多文檔在這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.