簡體   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