如題,
會顯示connect to db, app listening on port 3000
連接到資料庫,
到資料庫裡面看也的確有資料
以下是目前的程式碼,懇請各位大大解答,謝謝
db.js
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const dbname = "curd_mongodb";
const url = "mongodb://localhost:27017";
const mongoOptions = {useNewUrlParser: true};
const state = {
db: null
};
const connect = (cb)=>{
if(state.db)
cb();
else{
MongoClient.connect(url,mongoOptions,(err,client)=>{
if(err)
cb(err);
else{
state.db = client.db(dbname);
cb();
}
});
}
}
const getPrimaryKey = (_id)=>{
return ObjectID(_id);
}
const getDB = ()=>{
return state.db;
}
module.exports = {getDB,connect,getPrimaryKey};
app.js
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
const path = require('path');
var url = require('url');
const db = require("./db");
const collection = "todo";
db.connect((err)=>{
if(err){
console.log('unable to connect to db');
process.exit(1);
}else{
app.listen(3000,()=>{
console.log('connect to db, app listening on port 3000');
});
}
});
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname,'index.html'));
});
// read
app.get('/getTodos',(req,res)=>{
// get all Todo documents within our todo collection
// send back to user as json
db.getDB().collection(collection).find({}).toArray((err,documents)=>{
if(err)
console.log(err);
else{
res.json(documents);
}
});
});