gpt4 book ai didi

javascript - 为什么我在应用程序中使用 mongoose 时无法检索任何结果

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:10 24 4
gpt4 key购买 nike

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);

最佳答案

只需更改保存时的代码行即可返回错误和数据:

 vehicle.save(function(err, data) {
if (err) {
res.send(err);
}else{
console.log(data);
res.json({ messege: 'Vehcile is READY....!', data: data })
}});

关于javascript - 为什么我在应用程序中使用 mongoose 时无法检索任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46305523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com