所以我目前正在学习如何用Node Js和MongoDB构建一个Rest API,所以很自然地我一直在遵循一些教程,当时间到来时,我已经设置了一个示例,但它不起作用。
我有 2 个主要文件,应用程序.js和历史.js(模型(。
在应用程序上.js我有以下内容:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.json());
Historic =require('./models/historic');
// Connect to Mongoose
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
var db = mongoose.connection;
console.log('Here');
db.on('error', function(err){
if(err){
console.log(err);
throw err;
}
});
db.once('open', function callback () {
console.log('Mongo db connected successfully');
});
app.get('/', (req, res) => {
res.send('Please use /api/historic');
});
app.get('/api/historics', (req, res) => {
Historic.getHistorics((err, historic) => {
if(err){
throw err;
}
res.json(historic);
});
});
app.listen(27017);
console.log('Running on port 27017...');
然后在我的模型上,我有以下内容:
const mongoose = require('mongoose');
// Historic Schema
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
const Historic = module.exports = mongoose.model('Historic', historicSchema);
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
每当我尝试访问 http://localhost:27017/api/historics/时,我只会得到:[]。
我知道我的数据库上有数据,如您在图像上看到的那样:数据库测试数据
有什么提示吗?
根据 Docs http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html,回调至少应该是 .find 方法的第二个参数。尝试替换
// Get Historics
module.exports.getHistorics = (callback, limit) => {
console.log('Get Historics-Historic');
Historic.find(callback).limit(limit);
console.log('Get Historics-Historic-After find');
console.log(limit);
}
自
// Get Historics
module.exports.getHistorics = (callback, limit) => {
var query = Historic.find({});
query.limit(limit);
query.exec(callback);
}
我被告知解决方案并且它有效。
旧代码:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
});
溶液:
const historicSchema = mongoose.Schema({
_id:{
type: String,
required: true
},
url:{
type: String,
required: true
},
price:{
type: String,
required: true
},
timestamp:{
type: String,
required: true
}
}, {collection: 'historic'});
我需要添加在猫鼬上定义的集合名称