繁体   English   中英

使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 与 MongoDB 的 NodeJS 连接

[英]NodeJS connection with MongoDB using Mongoose

我正在尝试通过访问 localhost:4000/books 在浏览器 URL 中查看 mongodb collections(仅供查看)

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 属性中启动

运行>节点应用程序控制台显示消息为“应用程序正在侦听端口 4000 数据库已连接:mongodb://localhost:27017/example”

在 URL 中,当我尝试像这样访问 localhost:4000/books

显示错误为

参考错误:未定义 exec。 为什么会这样,请帮助解决这个问题。 我正在努力纠正这个错误 3 天,并在没有继续前进的情况下真正解决这个问题。

使用. exec之前尝试这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM