[英]NodeJS connection with MongoDB using Mongoose
I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books我正在尝试通过访问 localhost:4000/books 在浏览器 URL 中查看 mongodb collections(仅供查看)
app.js code: 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 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和 mongodb 服务器在 cmd 属性中启动
ran> node app console displayed messages as "app listening on port 4000 Database connected: mongodb://localhost:27017/example"运行>节点应用程序控制台显示消息为“应用程序正在侦听端口 4000 数据库已连接:mongodb://localhost:27017/example”
in URL, when I tried to access like this localhost:4000/books在 URL 中,当我尝试像这样访问 localhost:4000/books
display error as显示错误为
reference error: exec is not defined.参考错误:未定义 exec。 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.我正在努力纠正这个错误 3 天,并在没有继续前进的情况下真正解决这个问题。
use .
使用.
before exec
just try like this在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.