mongoose.connect('mongodb://localhost:27017/codealong');
这是我连接到MongoDB的方式,当我开始发布任何数据是成功但没有结果,并在我的浏览器中
只是得到那样的结果 [] 空方括号
这是我的依赖
"dependencies": {
"body-parser": "^1.18.1",
"express": "^4.15.4",
"mongoose": "^4.11.12",
"nodemon": "^1.12.1"
}
这是我的server.js文件
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Vechile = require('./app/models/vich');
var router = express.Router();
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var port = process.env.PORT || 3000
mongoose.connection.openUri('mongodb://localhost:27017/codealong')
.once('open', () => console.log('Good to go !'))
.on('error', (error) => {
console.warn('Warning', error);
});
app.use('/api', router);
router.use(function(req, res, next) {
console.log('There is something happens in the Background');
next();
});
//test router
router.get('/', function(req, res) {
res.json({ messege: 'Welcome to our Api' });
});
router.route('/vechicles')
.post(function(req, res) {
var vehicle = new Vechile(); //new instance from vehcile
vehicle.make = req.body.make;
vehicle.model = req.body.model;
vehicle.color = req.body.color;
vehicle.save(function(err) {
if (err) {
res.send(err);
}
res.json({ messege: 'Vehcile is READY....!' })
});
})
.get(function(req, res) {
Vechile.find(function(err, vehciles) {
if (err) {
res.send(err);
}
res.json({ vehciles });
});
});
router.route('/vehc/:id')
.get(function(req, res) {
Vechile.findById(req.params.id, function(err, vehcile) {
if (err) {
res.send(err);
}
res.json(vehcile);
});
});
router.route('/vehc/make/:make')
.get(function(req, res) {
Vechile.find({ make: req.params.make }, function(err, vehcile) {
if (err) {
res.send(err);
}
res.json(vehcile);
});
});
router.route('/vehc/color/:color')
.get(function(req, res) {
Vechile.find({ color: req.params.color }, function(err, vehcile) {
if (err) {
res.send(err);
}
res.json(vehcile);
});
});
app.listen(port, function() {
console.log('Server is running on port: ' + port);
});
这是mongoose模块
var mongoose = require(' mongoose'); var Schema = mongoose.Schema;
var VichSchema = new Schema({ make:String, model:String, color:String });
module.exports = mongoose.model(' Vichle',VichSchema);
答案 0 :(得分:0)
只需在保存时更改代码行即可返回err和数据:
vehicle.save(function(err, data) {
if (err) {
res.send(err);
}else{
console.log(data);
res.json({ messege: 'Vehcile is READY....!', data: data })
}});
答案 1 :(得分:0)
在模型中放入
module.exports = mongoose.model('Vichle', VichSchema);
通过Vechile更改Vichle