Why didn't I need to connect to database - node.js

I am new to web development. I just made a user model and then required into the main app.js file. But I saw that while making the user model I didn't need to connect to the database for it but I have connected the database to the app.js file. Then I saw how to require() works I found that it first runs the module/file which we had required and then return the object which that file returns. So I thought that it must throw an error because it wouldn't have fount the connection to the database while making the user model.
var mongoose=require('mongoose');
var passportlocalmongoose=require('passport-local-mongoose');
var userschema=new mongoose.Schema({
username:String,
password:String
});
userschema.plugin(passportlocalmongoose);
module.exports=mongoose.model('User',userschema);

you're not connected because you're not providing the required parameter,
here , there are some steps you can use.
first of all install express, mongoose and dotenv dependencies, and you will need a database URL in .env file
import express from 'express';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
const app = express();
dotenv.config();
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => process.stdout.write('DB Connection succesfully\n'));
const port =3000
app.listen(port, () => process.stdout.write(`Listening on port ${port} ... \n`));
export default app;

Related

Connect to MongoDB cluster

Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));

How to connect to a MongoDB in React, Typescript using Docker

I have a web app in on container, and mongoDB running in another. I would like to use mongoDB as the backend for my webapp but I can't seem to connect the two.
I am using docker compose to run both from one command.
Using mongoose.connect() threw errors because of typescript, and mongodb.MongoClient() gave 'ReferenceError: SharedArrayBuffer is not defined'. Does anyone know of a working method to connect to a MongoDB in this scenario?
import mongoose from 'mongoose'
shows "Could not find a declaration file for module 'mongoose'" even though its npm installed and in package.json.
I know the ports are visible because I can access both through the browser.
const mongoose = require('mongoose'); can't find package mongoose
I think I have some nasty mess of dependencies which may be messing everything up.
Thank you for any help
current index.js
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import mongodb from 'mongodb';
import * as Mongoose from "mongoose";
//const mongoose = require('mongoose')
//var db = new mongodb.MongoClient('mongodb://nosnes');
//var mongoclient = new mongodb.MongoClient('mongodb://mongo:27017',{} );
var uri = 'mongodb://mongo:27017';
Mongoose.connect(uri);
// //Mongoose.connect(uri, {
// useNewUrlParser: true,
// useFindAndModify: true,
// useUnifiedTopology: true,
// useCreateIndex: true,
// });
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
current error

Getting an error: "querySrv ECONNREFUSED _mongodb._tcp.cluster0.vxgqt.mongodb.net" when connecting to mongodb atlas

I am getting the below error in the terminal:
Error: querySrv ECONNREFUSED _mongodb._tcp.cluster0.vxgqt.mongodb.net did not connect
on running the index.js file
It was working fine till yesterday and today on running it is giving this error.
This is the code snippet:
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb+srv://<username>:<password>#cluster0.vxgqt.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
NOTE: I have provided the correct username and password in the connection url
I found a temporary fix and that is working: Under connect your application in MongoDB Atlas I selected node version 2.2.12 or later instead of 3.6 or later(which I used earlier). By selecting this, the application is now working fine as before
First of all check your internet connection and then go to mongodb Atlas and check whether your ip address is available in whitelist or not.
for testing purpose allow all ip's to access and then connect again.
querySrv ECONNREFUSED means that the attempt to resolve the SRV record failed to connect to a name server.
This is a DNS problem. Your application will need to be able to resolve the SRV record for _mongodb._tcp.cluster0.vxgqt.mongodb.net in order to use the mongodb+srv connection string.
you need to write your username and password inside URI of mongoDB, that mean u need to take value of CONNECTION_URL constant variable and change to current username of your account on mongoDB and change to current password of your account on mongoDB

Cannot connect mongoose with express rest api

I'm trying to create a rest api with express and connect to mongodb, I create a script to do the job and import it in the app.js file :
app.js
import express from 'express'
import morgan from 'morgan'
import dotenv from 'dotenv'
import mongoose from './config/mongoose.connection.js'
import logger from './config/logger.js'
import { port, env } from './config/vars.js'
const app = express();
app.use(express.urlencoded({
extended: true
}));
app.use(dotenv.config)
// start server
app.listen(port, () => {
logger.info(`server started on port ${port} (${env})`)
console.log('Server listening on port ' + port);
});
// open mongoose connection
mongoose.connectDB();
mongoose.connection.js
import { Promise as _Promise, connection, set, connect } from 'mongoose';
import { error } from './logger.js';
import { mongo, env } from './vars.js';
// set mongoose Promise to Bluebird
_Promise = Promise;
// Exit application on error
connection.on('error', (err) => {
error(`MongoDB connection error: ${err}`);
process.exit(-1);
});
// print mongoose logs in dev env
if (env === 'development') {
set('debug', true);
}
/**
* Connect to mongo db
*
* #returns {object} Mongoose connection
* #public
*/
export function connect() {
connect(mongo.uri, {
useCreateIndex: true,
keepAlive: 1,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log('mongoDB connected...'));
return connection;
}
when run the app I got this error :
file:///home/sahnoun/Documents/Fwinr-BACKEND/src/config/mongoose.connection.js:25
export function connect() {
^
SyntaxError: Identifier 'connect' has already been declared
Always look at the error which is explicit enough in that case:
connect' has already been declared
You can see that you are importing the function connect as well as exporting a function named connect. Just rename your function.
export function connectToMongo() {
connect(mongo.uri, {
useCreateIndex: true,
keepAlive: 1,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log('mongoDB connected...'));
return connection;
}
Bonus
If you want to keep your function name connect, then in the import, use something like:
import { Promise as _Promise, connection, set, connect as connectToMongo } from 'mongoose';
export function connect() {
connectToMongo(mongo.uri, {
...

How to use .env with ES6 module with node js and express application?

I need your help on how I can use .env file on this application. here is my problem: I am building an app using ES6 module in my node express app. I am facing a problem while storing my variable in .env file, both these two ways below are giving this error : MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. did not connect. But when I only use the plain string connect is working, that means that I am not using the dotenv file correctly:
1-
import {} from "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.listen(port,()=>console.log(`server on ${port}`)
2-
import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
dotenv.config();
const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.listen(port,()=>console.log(`server on ${port}`)
Here is how to use it as ES6 module
import * as dotenv from 'dotenv';
dotenv.config();
If you don't need the return value from the dotenv.config() function, you can use this pattern to execute the config function as a side-effect of the import:
import 'dotenv/config';
I recommend this syntax because it improves compatibility with Typescript compilers that are strict about the ESM spec (i.e. SWC) and also provides better compatibility with code-formatting rules that want to re-order your import statements.
Path is default to ./root/.
To add path to current directory (Dir), we need this code inside of the file that we want all variables to be imported
import dotenv from 'dotenv'
import path from 'path'
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '.env') });
// const express = require('express')
import express from 'express';
server.js and .env can should be in the same directory if you don't manipulate the path.join(__dirname.
You can reach the variables process.env.myvariable. Just be sure it works and print all variables: console.log(process.env)
Thanks
You are right, you are not fetching the env variables.
I'll tell you how I do it. Just create a .env file with your variables.
Then in your app.js:
const dotenv = require('dotenv');
dotenv.config();
And to use the variable uri you have in the .env
const foo = process.env.uri

Resources