我剛開始學習使用 node JS,我在本地使用社區版本的 mongdb 將 mongoose 連接到 mongodb 時遇到了困難。
const app = express();
app.use(bodyParser.json({extended: true}))
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
app.get('/', (req, res)=>{
react
})
const connectDB = 'mongodb://127.0.0.1/mydb';
mongoose.connect(connectDB, {useNewUrlParser: true, useUnifiedTopology:true}) //set up default mongoose connection
let db = mongoose.connection; //Get the connection
db.on('err', console.error.bind(console, 'MongoDB connection error:')); //Bind connection to error event
每當我運行服務器時,我看不到任何資料庫已連接的跡象,也沒有任何錯誤,連接不會發生。這是我在運行服務器時在控制臺上看到的內容
C:\projects\mongodb\backend>nodemon Server.js
> backend@1.0.0 start
> nodemon Server.js
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node Server.js`
啟動服務器的程序永遠不會完成。
uj5u.com熱心網友回復:
您可以使用以下代碼,
const mongoose = require('mongoose');
mongoose.connect(db_url,{ useNewUrlParser: true }, function (err) {
if (err) throw err; console.log('Successfully connected'); });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371858.html
上一篇:NestJS,Mongoose-時間戳回傳毫秒而不是秒
下一篇:MongoDb唯一約束問題
