我正在为博客应用程序和API创建API,我将通过它获取所有博客,显示一些错误。我的app.js(这是API文件)和blogModel.js(它是模式文件)写在下面。请帮助我找到错误。
///////////////////app.js/////////////////////////
//calling the module
var express = require('express');
//cretaing an instance
var app = express();
//calling body-parser and cookie-parser
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//calling mongoose module
var mongoose = require('mongoose');
var newBlog = [];
//using body-parser and cookie-parser
app.use(bodyParser.urlencoded({limit : '10mb', extended : 'true'}));
app.use(bodyParser.json({limit : '10mb', extended : 'true'}));
app.use(cookieParser());
//Defining configuration of mongoDB or at BlogApp it will create Database
var dbPath = "mongodb://localhost/BlogApp";
//Telling mongoDB to connect at dbPath or connect database
db = mongoose.connect(dbPath);
//Checking connection is open or not
mongoose.connection.once('open', function () {
console.log("connection is established");
})
//Including the schema file or Blog Model file
var Blog = require('./blogModel.js');
//To play with the data which will be store in blog or perform various functions on db using
//blogData variable
var blogData = mongoose.model('Blog');
//A simple route to check app is working or not correctly
app.get('/', function(req, res){
res.send("Application in on and it's working very fine. Stay in touch to get latest updates");
})
//Mian routes fro blog Application
//1.) Route to get all the blogs
app.get('/blogs',function(req, res) {
blogData.find(function(err,result){
if(err) {
console.log(err);
}
else {
console.log(result);
res.send(result);
}
})
});
//2.) Route to create a Blog
app.listen(3000, function(){
console.log("Listening on port 3000");
})
///////////blogModel.js///////////////////////
//Calling the module
var mongoose = require('mongoose');
//using the schema part of the module
var blogSchema = mongoose.Schema;
//creating an instance
var blogData = new blogSchema({
blogId : {type : String, default : ''},
blogCreatedOn : {type : Date, default : null},
blogHeading : {type : String, default : ''},
blogSubHeading : {type : String, default : ''},
blogBody : {type : String, default : ''},
imageUrl : {type : String, default : 'https://www.google.com'},
blogAuthorName : {type : String, default : ''}
});
//blogData is schema name
mongoose.model('Blog', blogData);

我的错误是: - =>未定义blogSchema。
请帮帮我。 提前致谢
答案 0 :(得分:0)
您应该导出模型以便能够要求它。所以在blogModel.js
文件中改变了这个:
mongoose.model('Blog', blogData);
到这一个:
module.exports = mongoose.model('Blog', blogData);
在您的app.js中使用Blog
进行查询:
var Blog = require('./blogModel.js');
// var blogData = mongoose.model('Blog');
//1.) Route to get all the blogs
app.get('/blogs',function(req, res) {
Blog.find(function(err,result){ ...