简体   繁体   中英

NodeJS connection with MongoDB using Mongoose

I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books

app.js code:

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

and the mongodb server started in cmd propt

ran> node app console displayed messages as "app listening on port 4000 Database connected: mongodb://localhost:27017/example"

in URL, when I tried to access like this localhost:4000/books

display error as

reference error: exec is not defined. why is that, please help on this issue. I am working on rectify this erro for 3 days and really stcuk on this without moving forward.

use . before exec just try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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