
上QQ阅读APP看书,第一时间看更新
Connecting the server to MongoDB
To connect your Node server to MongoDB, add the following code to server.js, and make sure you have MongoDB running in your workspace.
mern-simplesetup/server/server.js:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI || 'mongodb://localhost:27017/mernSimpleSetup'
MongoClient.connect(url, (err, db)=>{
console.log("Connected successfully to mongodb server")
db.close()
})
In this code example, MongoClient is the driver that connects to the running MongoDB instance using its url and allows us to implement the database related code in the backend.