我试过多种东西,我无法弄清楚我做错了什么。我是后端服务新手,不确定从哪里开始寻找问题。MongoDB和快速呼叫不工作
app.js
// SERVER SETUP
var express = require ('express');
var bodyParser = require ('body-parser');
var app = express();
var router = express.Router();
var routes = require('./routes');
var transactions = require('./routes/routes');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
//API ROUTES
router.use(function (req, res, next){
console.log('Something is happening. . .');
next();
});
// REGISTER ROUTES
app.use('/', router);
app.get('/transactions', transactions.getRecords);
// START THE SERVER
app.listen(port);
console.log('Server is running on port ' + port);
model.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function (callback){
console.log('Mongo Connected');
});
var Schema = mongoose.Schema;
var BankSchema = new Schema({
_id: String,
date: Date,
account: String,
location: String,
amount: Number,
type: String,
reason: {
type: String,
explanation: String
}
});
exports.transactions = mongoose.model('BudgetApp', BankSchema, 'transactions');
routes.js
var useModel = require('./model');
var bankData = useModel.transactions;
var transactions = function (callback){
var records = []
bankData.aggregate([
{$match: {type:"debit"} },
{$group:{
_id:{
month: {$month: "$date"},
year:{$year: "$date"}
},
expense: {
$sum:"$amount"
}
}
},
{$project: {
date: "$_id",
spent: "$expense"
}}
], function (err, data){
if (err){ console.log(err);}
console.log(data);
records.push(data);
});
callback(records);
};//transactions
exports.getRecords = function (req, res){
transactions(function (err, transaction){
if (err){console.log(err);}
res.json(transaction);
});
};
当运行节点服务器,控制台日志仅回报和空数组,没有错误。我不知道我做错了什么。
你已经提到了localhost。但你配置了本地主机url的端口?如果没有,那么尝试把你的mongo服务器运行的端口号。请让我知道它是否有帮助。 :) – Abhishek
我甚至不确定我的URL是否正确或者如何为mongodb设置url – Obsanity
如果您刚刚在他们的教程中安装了Mongo数据库,那么只需将“mongoose.connect('mongodb:// localhost/test')“与”mongoose.connect('mongodb:// localhost:27017/test')“。试试看,让我知道。 – Abhishek