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
mongoose.connect(mongoURI);
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;
},
};
npm install mongodb --save
const MongoClient = require('mongodb').MongoClient
const start = async () => {
if (!process.env.DB_URI) {
throw new Error('auth DB_URI must be defined');
}
try {
await mongoose.connect(process.env.DB_URI!, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('Server connected to MongoDb!');
} catch (err) {
throw new DbConnectionError();
console.error(err);
}
const PORT = process.env.SERVER_PORT;
app.listen(PORT, () => {
console.log(`Server is listening on ${PORT}!!!!!!!!!`);
});
};
start();
Run code snippetHide results