iT邦幫忙

2

已連接Mongodb但不能讀取data

如題,
會顯示connect to db, app listening on port 3000
連接到資料庫,
到資料庫裡面看也的確有資料

https://ithelp.ithome.com.tw/upload/images/20190731/201118732OT6sSH0uu.jpg
以下是目前的程式碼,懇請各位大大解答,謝謝

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

1 個回答

1
dragonH
iT邦超人 6 級 ‧ 2019-07-31 23:40:27
最佳解答
const dbname = "curd_mongodb";

crud_mongodb !== curd_mongodb
p39212053 iT邦新手 5 級 ‧ 2019-07-31 23:43:12 檢舉

抱歉問了蠢問題T_T,謝謝幫忙

辛苦了! 一槍斃命..

dragonH iT邦超人 6 級 ‧ 2019-08-01 13:32:48 檢舉

/images/emoticon/emoticon82.gif

我要發表回答

立即登入回答