How does module.exports = mongoose; work when requiring "./database"? - javascript

I'm a MERN stack beginner. I came across this snippet of code from a basic CRUD and I know that it works, but I don't get how.
//in server.js
const database = require('./database');
//in database.js
const mongoose = require('mongoose'); //importing mongoose
mongoose.connect('mongodb://localhost/monguse', {useNewUrlParser:true}) //connected to db
.then((db)=>{console.log('Database connected')}) //message if ok
.catch((err) =>{console.log(`Database connection error: ${err}`)}); //catching errors
module.exports = mongoose;
I understand what is going on in database.js (It is my own version), but why does it work without using any method in server.js? It appears to make the connection only from using the "require" function. then in my routes there is no mention of that again; just using mongoose models in the requests.
Thanks!

In database.js you create an instance of the database and export it by name mongoose, and in server.js you are importing that instance of the mongoDB by name database.

Related

How dotenv Package Work With pg.Pool in NodeJS

I've read some code that uses the dotenv package to create configurations.
When I read a file that contains PostgreSQL code for Pool, the code looks like this:
const pg = require('pg')
const { Pool } = pg
// This pool was created without completing the pool connection configuration. 
const pool = new Pool()
However, I see that this pool configuration is written in the.env file. 
#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432
and .env file is called once in main file :
// main file
require('dotenv').config()
const express = require('express')
// below is the server
Why is a pool created without passing any configuration objects as arguments?
How does it work in the background?
I still can't figure this out clearly.
I've tried searching for this behavior, but I haven't found it yet.
When you run
require('dotenv').config()
that sets everything in your .env file to be on process.env.*.
For example, you say PGUSER=username, so now process.env.PGUSER === "username"
pg.Pool seems to go with those environment variables by default

Connecting to MongoDB database

I am trying to connect to a MongoDB database.I have followed all the steps here https://youtu.be/EcJERV3IiLM but am getting an error.
The index.js file looks like this,
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, async function(err,client){
const db = client.db()
const results = await db.collection("student").find().toArray()
console.log(results)
The error I get is,
mongodb.connect is not a function
So it seems to be reading as far line 5:9 which is mongodb.connect in index.js and just stops.
I put this file index.js beside the .env file and beside that .gitignore which contains the the .env file. The .env file has the code which I copied from the Mongodb AtlSAS Cloud Service.
I also created a user and and autogenerated and saved a password. Both of which I placed in the string. And I put in the string the name of the database name "blah" The table/document is called "student". That's in the index.js code above. So the database name and the document name are blah.student.
I documented what I tried here, http://www.shanegibney.com/shanegibney/mongodb-setup/
The tutorial video is here, https://youtu.be/EcJERV3IiLM
I am on Ubuntu Linux.
I am currently running index.js in the terminal in a directory called mongostack, with
node index.js
but should I use,
nodemon index.js
And for this should I install nodemon and how do I do that?
Do I need to download it first and if so where do I get it?
I think you need to get MongoClient. Try changing:
const mongodb = require('mongodb')
to:
const mongodb = require('mongodb').MongoClient;
You have to create a MongoClient see https://www.mongodb.com/docs/drivers/node/current/quick-start/
const { MongoClient } = require("mongodb");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
async function run() {
await client.connect();
const db = client.db("yourdb")
const results = await db.collection("student").find().toArray()
console.log(results)
}
run();

MongoDB/Mongoose Connection Error when Dbname is used in the connection string

A NodeJS app uses mongoose 5.6.0 to connect to MongoDB 4.0.10 which runs on localhost inside a docker container.
The connection can be established when we use
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri)
Problem: We start getting authentication errors when we include the name of the database we are connecting to. There is no problem using Python to connect to the same MongoDB database.
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri)
and also tried
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db'
mongoose.connect(mongoUri, { useNewUrlParser: true })
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Authentication failed.
Why is it unable to make the connection and how can we solve this problem?
Update
Found the solution to be
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017'
mongoose.connect(mongoUri, { useNewUrlParser: true, dbName: 'my-db' })
Why must the dbname be passed as an option instead of including it in the connection string?
This has worked for me, thanks.
var result = await mongoose.connect('mongodb://root:example#localhost:27017/', {useNewUrlParser: true,dbName: 'my-db'})
Short answer: Add ?authSource=admin to URI string or use {authSource:"admin"}
const mongoUri = 'mongodb://admin:mypassword#127.0.0.1:27017/my-db?authSource=admin'
mongoose.connect(mongoUri)
Follow this answer https://stackoverflow.com/a/68137961/12280326 for detailed explanation.

How should in right way connecting MongoDB in Nodejs?

Hello i am new in Nodejs & MongoDb.
I created controllers for API where i want create new items in MongoDB, edit, search items.
Now i am connecting to MongoDB via mongoose in main file server.js.
But i need that i can create, edit in editor.js.
I tried to export mongoose module, but it was unsuccessfull.
How i can do this in right way?
my structure
`editor.js` file - where i want have access to database
const models = require('./../models');
const client = require('./../../server');
const mongoose = require('mongoose');
let db;
// const db = client.db('todo');
module.exports = {
getNewsById: async (req, res) => {
console.log(req.params);
// console.log(req);
res.send({oK: 'ok'});
},
createNews: async (req, res) => {
const newItem = req.body;
newItem['publishedAt'] = Date.now();
console.log('HERE', client);
console.log('HERE2', client.db.collection('test').insertOne({
item: 'canvas',
qty: 100,
tags: ['cotton'],
size: { h: 28, w: 35.5, uom: 'cm' }
}));
}
}
In editor.js after importing mongoose, you can simply load your model using -
const db = require('mongoose');
const testModel = db.model('test');
And then you can call your db queries similar to -
testModel.insert(...);
testModel.find();
Once you have built your model using mongoose, it is available in the application. You just need to get it through mongoose.
If you need more help, you can refer to my sample project at https://github.com/kravigupta/nodejs-express-mongo-auth
For every new developer who is learning node.js, the first thing they go with the MongoDB connection with the node.js.
I will suggest you keep the MongoDB connection URL, username and password in a separate file say it db.config.js file and then import that file into you server.js or app.js or main file of your node.js and then connect mongo with the try catch block to handle the error. IF you need to learn in more details then you can refer to this link.

NodeJs can not find function

I have a NodeJs project, and some imported libraries are not working properly, namely bookshelf and pg. This problem does not seem to be coming from the libraries, since they are 'official' packages available via npm.
Here's one snippet that's not working properly:
var pg = require('pg');
pg.connect('postgres://postgres:password#localhost:5432/myproject');
giving me the following error:
pg.connect();
TypeError: pg.connect is not a function
Although the function connect() obviously exists and should be accessed that way according to the documentation.
This also happens with bookshelf. If I try something like this:
var knex = require('knex')({
client: 'mysql',
connection: {
host : 'localhost',
user : 'root',
password : 'mypw',
database : 'userdb',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var User = bookshelf.Model.extend({
tableName: 'user'
})
bookshelf.plugin('registry');
module.exports = bookshelf;
The IDE tells me that Model can't be found if I hover over it with the curser, and if I try to create a new entry in the database with
new User({username: 'test',
.... })
I get an error saying that
TypeError: User is not a constructor
Again, I have used the official documentation of the library bookshelf to create the last snippet.
I am also using express, hogan, bcrypt and they work perfectly fine.
What could be the problem here?
About the problem of connect function:
var pg = require('pg');
var conString = "postgres://postgres:password#localhost:5432/myproject";
var client = new pg.Client(conString);
client.connect();
The connect function is declared in Client
Follow this link with more documentation about node-postgres package https://github.com/brianc/node-postgres

Categories