xxxxxxxxxx
const MongoClient = require('mongodb').MongoClient
xxxxxxxxxx
1 mongo # connects to mongodb://127.0.0.1:27017 by default
2 mongo --host <host> --port <port> -u <user> -p <pwd> # omit the password if you want a prompt
3 mongo "mongodb://192.168.1.1:27017"
4 mongo "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --username <username> # MongoDB Atlas
xxxxxxxxxx
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db("sample_airbnb");
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
Connect to mongoDB database
xxxxxxxxxx
const { MongoClient } = require("mongodb");
// Connection URI
const uri = "<connection string uri>";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
xxxxxxxxxx
const MONGO_URI = "mongodb-uri"
import mongoose from 'mongoose';
const connectMongo = async () => {
try{
const { connection } = await mongoose.connect(MONGO_URI)
if(connection.readyState == 1){
console.log("Database Connected")
}
}catch(errors){
return Promise.reject(errors)
}
}
export default connectMongo;
xxxxxxxxxx
import { Router } from 'express';
import { ObjectID } from 'mongodb';
const router = new Router();
router.get('/:id', async (req, res, next) => {
try {
const db = req.app.locals.db;
const id = new ObjectID(req.params.id);
const user = await db.collection('user').findOne({ _id: id }, {
email: 1,
firstName: 1,
lastName: 1
});
if (user) {
user.id = req.params.id;
res.send(user);
} else {
res.sendStatus(404);
}
} catch (err) {
next(err);
}
});
export default router;
xxxxxxxxxx
// Connect to MongoDB
const mongoConnection = new DatabaseConnection();
await mongoConnection.connect();