当我发出localhost:8000 / api / customers时,即使我在mongodb中插入数据,我也会得到空数组。我测试了路由localhost:8000 / api / customers而没有连接到mongodb,它显示一个静态文本。但是,当连接到Mongodb时,它返回空数组。这是代码
var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection err'));
db.once('open', function callback(){console.log('connected to db')});
var Customer = require('./Customers/models/customerModel');
var app = express(),
port = process.env.PORT || 3000,
customerRouter = express.Router();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
customerRouter.route('/Customers')
.post(function(req, res){
var customer = new Customer(req.body);
console.log(customer);
res.send(customer);
})
.get(function(req,res){
Customer.find(function(err,customers){
if(err)
res.status(500).send(err);
else {
res.json(customers);
console.log(customers);
}
});
});
app.use('/api', customerRouter);
app.get('/', function (req, res) {
res.send('Welcome to my API')
});
app.listen(port, function () {
console.log('Running on port ' + port);
});
和customerModel.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var customerModel = new Schema({
name: {type: String},
contact: {type: String},
date_register: {type: String},
main_tel: {type: String},
tel_1: {type: String},
tel_2: {type: String},
tel_3: {type: String},
address: {type: String},
email: {type: String}
});
module.exports = mongoose.model('Customer', customerModel);
我在端口8000上使用gulp task runner
答案 0 :(得分:0)
您没有正确使用Customer.find
。查看文档:
http://mongoosejs.com/docs/api.html#model_Model.find
find()
应该有两个参数。第一个参数是find方法的条件(如果你愿意,则为“WHERE”条件),第二个参数是回调。更新您的代码:
Customer.find(function(err,customers){ ...
到此:
Customer.find({}, function(err,customers){ ...
传递空物体意味着“给我一切”。如果您以后想要找到名为“John”的所有客户,您可以这样做:
Customer.find({firstName: "John"}, function(err,customers){ ...
答案 1 :(得分:0)
好的我解决了,我错过了POST中的customer.save(cb(错误))。现在GET正在运作。谢谢大家