Sunday, September 25, 2022

Connect to local MongoDB database

// mongoose do not work globally => install into project

// needed to import mongoose in both cases

npm i mongoose

const mongoose = require('mongoose');

// with Mongoose

const dbUrl = 'mongodb://127.0.0.1:27017/_db';
(async () => {
try {
await mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then((con) => {
console.log(con.connection);
console.log(`MongoDB connected: ${dbUrl}`);
});
} catch (err) {
console.error(err);
}
})();

// with MongoClient

const dbUrl = 'mongodb://127.0.0.1:27017/_db';
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(
dbUrl,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) {
return console.log(err);
}

// Specify database you want to access
const db = client.db('_db');

console.log(`MongoDB Connected: ${dbUrl}`);
}
);

DATABASE_LOCAL=mongodb://user:pass@127.0.0.1:27017/_db

https://mongoosejs.com/docs/connections.html

https://zellwk.com/blog/local-mongodb/

https://stackoverflow.com/questions/54573548/how-to-connect-to-mongodb-in-local-network-with-express-and-mongoose

No comments:

Post a Comment