【发布时间】:2021-05-12 08:04:00
【问题描述】:
我正在尝试通过访问 localhost:4000/books 在浏览器 URL 中查看 mongodb 集合(只是为了查看)
app.js 代码:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Book = require("./book.model");
//mongo DB database connection: databse nmae is: example
var db = "mongodb://localhost:27017/example";
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
const conSuccess = mongoose.connection
conSuccess.once('open', _ => {
console.log('Database connected:', db)
})
conSuccess.on('error', err => {
console.error('connection error:', err)
})
var port = 4000;
app.listen(port, function () {
console.log("app listening on port " + port);
});
//REST get
app.get('/', function(req,res){
res.send("happy to be here");
});
//work on here localhost:4000 works but not localhost?4000/books
//get all "books" collections
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({})
exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});
book.model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
category: String,
});
module.exports = mongoose.model("Book", BookSchema);
mongodb 服务器在 cmd propt 中启动
ran> 节点应用 控制台显示消息为 “应用程序监听 4000 端口 数据库连接:mongodb://localhost:27017/example"
在 URL 中,当我尝试这样访问时 本地主机:4000/书
将错误显示为
引用错误:exec 未定义。为什么会这样,请帮助解决这个问题。我正在努力纠正这个错误 3 天,并在没有继续前进的情况下真正解决这个问题。
【问题讨论】:
标签: node.js mongodb express mongoose