xxxxxxxxxx
const {
MongoClient
} = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://demo:demo@cluster0we.q3ewewmt5wj.mongodb.net/?retryWrites=true&w=majority";
// 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({
dbStats: 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 {
MongoClient
} = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://demo:demo@cluster23.q3323m24t53wj.mongodb.net/?retryWrites=true&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
await listDatabases(client);
console.log("Connected successfully to Mongo server");
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client) {
const databasesList = await client.db().admin().listDatabases();
console.log("Databases:")
databasesList.databases.forEach(db => {
console.log(`- ${db.name}`);
});
}
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;
},
};
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;