NodeJs can not find function - javascript

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

Related

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

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.

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.

'TypeError: Object is not a function' when using tunnel-ssh

I'm running the basic example in the tutorial for the popular NPM package tunnel-ssh. Here is the code:
var tunnel = require('tunnel-ssh');
var config = {
username:'root',
password:'secret',
host:'remote.mysql.server.com',
port:3306
}
tunnel(config, function(e, sshTunnel){
//Now, you should be able to connect to the tunnel via localhost:3336.
});
I am running it with the credentials for my own database of course. However, I always get this error when I run it:
TypeError: object is not a function
Anybody know what's going on?
var tunnel = require('tunnel-ssh');
var config = {username: 'vagrant',host: '192.168.33.2', port:3307, dstPort:3306 }
tunnel.tunnel(config, function(e, sshTunnel){});
I have my key added in 192.168.33.2 and forwarding the destination port 3306 to my local port 3307.
I am running this on RPEL node version v0.12.4. Its working.

How do you set and retrieve an instance of BookshelfJS using Express?

I'm trying to use Bookshelf along with Express 4.0 and can't seem to get them working together or rather, I can't seem to follow "best practices". The Bookshelf docs mention that one should always reuse the same instance of it throughout the app. It even lists an example:
// When the app starts
var app = express();
var knex = require('knex')(dbConfig);
var bookshelf = require('bookshelf')(knex);
app.set('bookshelf', bookshelf);
// elsewhere, to use the bookshelf client:
var bookshelf = app.get('bookshelf');
var Post = bookshelf.Model.extend({
// ...
});
However, I can't seem to get it working when I have to use app.get() in a separate file. For example, here's my app.js file (the root of my entire app):
var express = require('express');
var app = express();
var db = require('./server/db/db');
app.set('bookshelf', db);
var api = require('./server');
app.use(api);
Here's my db.js file that gets required above:
var express = require('express');
var app = express();
var knex = require('knex')({ //my db settings go here });
var bookshelf = require('bookshelf')(knex);
module.exports = bookshelf;
The above code works if I require it directly. Here's where the issue turns up. Whenever I want to actually use the bookshelf connection, no matter what file I'm in, I follow the same process but it fails and "bookshelf" is always undefined. Here's an example of an index.js file that's required and called "api" in the app.js:
var express = require('express');
var app = express();
var db = app.get('bookshelf');
console.log(db);
DB always comes up as undefined. Whenever I try to make a new Model, I use the same process except I do an db.Model.extend({}) and trying to access the Model property throws an error (because it's undefined).
From what I can use both Bookshelf and Express docs agree that this should work and it doesn't. Any ideas?
This line creates a new app every time you call it:
var myApp = express();
If you want to set or get variables from the same app, you'll have to pass it as an argument.
var api = require('./server')(myApp);
And then in your api module:
module.exports = function(app){
var db = app.get('bookshelf');
//....
};
On a side note: you don't have to worry about singletons in Node.js all you have to do is just require it.
var db = require('./path/to/db/config');
It'll only be instantiated once and cached for later calls.

Categories