我想用Mongoose与MongoDB挂钩,在Express中定义和使用API。到目前为止,我将对象保存为前端的精细形式输入。但是,当检索和显示我保存的数据时,我似乎迷失了。
以下是一些代码:
db.js:
const mongoose = require('mongoose');
//mongoose setup
mongoose.connect(mongooseUrl, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('mongoose connected to ' + mongooseUrl);
});
module.exports = db;
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// import routers
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
/routes/api.js:
var express = require('express');
var mongoose = require('mongoose');
var db = require('../config/db.js');
var Kitten = require('../models/kitten.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('api', {
title: 'Test API',
content: 'you\'re in the right place',
buttontext: 'send POST request'
});
});
router.post('/newKitten', function(req, res, next) {
var kitty = new Kitten({
name: req.body.name,
color: req.body.color
});
console.log("new kitty: " + kitty.name + " color: " + kitty.color );
kitty.save().then(console.log(kitty + " was saved to the database"));
res.send('new: ' + kitty);
});
router.get('/kittens', function (req, res, next) {
var kittens = Kitten.find({}, 'name color');
res.render('kittens', {title: 'Kittens', list_kittens: kittens });
});
module.exports = router;
models / kitten.js
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var kittenSchema = new Schema({
name: String,
color: String
});
var Kitten = mongoose.model("Kitten", kittenSchema);
module.exports = Kitten;
views / kitten.hbs:
<h1>{{title}}</h1>
<ul>
{{#each list_kittens as |kitten|}}
<li>name: {{kitten.name}}, color: {{kitten.color}}</li>
{{/each}}
</ul>
现在一切都摆好了,当我访问http://localhost:3000/api/kittens时,我看到的是:
我不知道为什么它不呈现我保存在MongoDB数据库中的小猫……数据在那里,但是我似乎对猫鼬应该如何查询数据感到困惑。任何和所有帮助表示赞赏。我已经坚持了几天。
答案 0 :(得分:3)
Model.find
返回一个承诺。您必须添加函数then
才能获得小猫并渲染它们:
Kitten.find(...)
.then(kittens => {
res.render(...)
})
编辑
基于@Francisco Mateo注释,Kitten.find
返回一个Query
,您可以使用exec
执行该操作。这是代码:
Kitten.find(...).exec()
.then(kittens => {
res.render(...)
})
答案 1 :(得分:2)
在routes / api.js中
var express = require('express');
var mongoose = require('mongoose');
var db = require('../config/db.js');
var Kitten = require('../models/kitten.js');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('api', {
title: 'Test API',
content: 'you\'re in the right place',
buttontext: 'send POST request'
});
});
router.post('/newKitten', function(req, res, next) {
var kitty = new Kitten({
name: req.body.name,
color: req.body.color
});
console.log("new kitty: " + kitty.name + " color: " + kitty.color );
kitty.save().then(console.log(kitty + " was saved to the database"));
res.send('new: ' + kitty);
});
router.get('/kittens', async function (req, res, next) { **//Change here**
var kittens = await Kitten.find({}, 'name color'); **//change here**
res.render('kittens', {title: 'Kittens', list_kittens: kittens });
});
module.exports = router;
Kitten.find({}, 'name color')
返回一个promise,因此您必须等待直到数据返回。