getting error : Cannot read property 'findOne' of undefined in node js - node.js

i have created sample page, and when i run my page node airbnb-library.js i am getting error, Cannot read property 'findOne' of undefined can anyone please help me why i am getting this error ? here i have attached my code, can anyone please look my code and help me to resolve this issue ? any help will be really appreciated...
db.js
const config = require('../config.json');
const mysql = require('mysql2/promise');
const { Sequelize } = require('sequelize');
module.exports = db = {};
initialize();
async function initialize() {
// create db if it doesn't already exist
const { host, port, user, password, database } = config.database;
const connection = await mysql.createConnection({ host, port, user, password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
// connect to db
const sequelize = new Sequelize(database, user, password, { host: host, port: port, dialect: 'mysql' });
// init models and add them to the exported db object
db.User = require('../users/user.model')(sequelize);
db.Airbnb = require('../users/airbnb.model')(sequelize);
// sync all models with database
await sequelize.sync();
}
airbnb-library.js
const http = require("http");
const requestapi = require('request');
const airbnb = require('airbnbapijs')
async function test() {
const airbnbdata = await airbnb.newAccessToken({ username: 'dino#pushideas.com', password: 'Christmas2016!'})
console.log(airbnbdata);
}
let airbnbdata = test();
main.js
const config = require('../../../config.json');
const airbnb = require('airbnbapijs')
const requestapi = require('request');
const http = require("http");
async newAccessToken({ username, password } = {}) {
try {
await this.airbnblogin({"email":username,"password":password});
} catch (e) {
console.log(e);
}
}
async airbnblogin(params) {
let account = await db.Airbnb.findOne({ where: { airbnb_email: params.email, } })
}

Related

Error node.js connecting to Postgres: client.query is not a function

I guess I am missing something quite obvious. Why cannot I query the db and I am getting this error:
TypeError: client.query is not a function
The code is quite simple:
const consts = require('./constants');
const bcrypt = require('bcrypt');
const process = require('process');
require('dotenv').config();
const { Client } = require("pg")
const command = "login_user"
const pass = "login_user"
const client = connectToDb();
if (command === consts.LOGIN_USER) {
loginUser(client, pass);
}
async function connectToDb() {
const dbClient = new Client({});
await dbClient.connect();
return dbClient;
}
async function loginUser(client, pass) {
const query = { text: 'SELECT * FROM users' }
const res = await client.query(query).rows;
console.log(res);
await client.end();
}
The credentials for the db are in the .env file.
I suppose the problem was that the connectToDb() function needs to be called from within an async function.
Here's the code which I got working:
handleInput();
async function handleInput() {
const client = await connectToDb();
if (command === consts.LOGIN_USER) {
await loginUser(client, username, pass);
}
await client.end();
}
async function connectToDb() {
const dbClient = new Client({});
await dbClient.connect();
return dbClient;
}
async function loginUser(client, username, pass) {
// Some operations with db
}

Connecting to mongodb in nodejs

I am first to use MongoClient to connect mongodb in nodejs, in each js file I use it like following
'use strict'
//part 1
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');
const Mongodb = {
client: new MongoClient(dbconfig.product.dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
}),
oper: null,
db: null,
dbName: '',
};
const dbConnect = async (dbName = dbconfig.product.dbName) => {
if (Mongodb.oper) {
if (dbName !== Mongodb.dbName) {
Mongodb.db = Mongodb.client.db(dbName);
Mongodb.dbName = dbName;
}
return Mongodb.db;
}
Mongodb.oper = await Mongodb.client.connect();
return await dbConnect(dbName);
};
//part 2
const db = await dbConnect();
let info = await db.collection.find({});
//more code
The situation is that there is a lot of duplicate code, such as part 1, and I want to put part 1 into a file and import it where needed. I have no idea how to do, give me some ideas please, thank you.
You only need to connect to db once. My advice would be - google and try mongoose. I find it easier. Google some examples and read the docs.
Create a JS module that exports the connect function using module.exports then require it where necessary, something like this:
// mongo.js
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');
const client = new MongoClient(dbconfig.product.dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let databasePromise;
async function _connect() {
try {
await client.connect();
} catch (e) {
console.error(e);
await closeConnection();
throw e;
}
return client.db();
}
function connect() {
if (!databasePromise) {
databasePromise = _connect();
}
return databasePromise;
}
async function close() {
await client.close();
databasePromise = undefined;
}
isConnected() {
return client.isConnected();
}
module.exports = {
connect,
close,
isConnected,
}
// index.js
const { connect } = require('./mongo');
(async () => {
const db = await connect();
const results = await db.collection('collection1').find({});
console.log(results);
})();
// file2.js
const { connect } = require('./mongo');
(async () => {
const db = await connect();
const results = await db.collection('collection2').find({});
console.log(results);
})();
Note, this code is not tested so it might need adjustments.

Nextjs MongoDB template: clientPromise is not a function

I am using Next.js's MongoDB example template and it comes with a MongoDB util function:
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI;
const options = {};
let client;
let clientPromise;
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local');
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;
Here is how I am using it and I am certain that I am using this incorrectly.
import { clientPromise } from '../../lib/mongodb';
export default async (req, res) => {
try {
const db = await clientPromise();
const users = await db.collection('users').find({}).limit(20).toArray();
res.json(users);
} catch (e) {
console.error(e);
res.json({ error: 'Not connected!' });
}
};
The error is "TypeError: (0 , lib_mongodb__WEBPACK_IMPORTED_MODULE_0_.clientPromise) is not a function"
You're exporting clientPromise, which is client.connect(). At this point you already "triggered" the connection function. now all you have to do is wait on that promise,
So instead of
const db = await clientPromise();
You should do:
const connection = await clientPromise; // this is a client connection not a db
const db = connection.db();

can not connect to documentDB aws from node js backend

I'm trying to connect my document DB from my node js backed
but the _mongoClient return as undefined.
I open the ssh and I have all the permissions I need but it's still not working and there is no error in the console.
can you please help?
this is my code:
const {MongoClient, ObjectID} = require('mongodb');
const fs = require('fs');
const path = require('path');
const filePath = path.resolve(__dirname,caFile)
const ca = [fs.readFileSync(filePath)];
let hostName = 'localhost';
let _mongoClient;
const baseurl = `mongodb://${username}:${password}#${hostName}:${port}/`;
let urlParams = `ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&retryWrites=false`;
const connectOptions = {
sslCA: ca,
useUnifiedTopology:true
}
_mongoClient = await MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions, function (err,client) {
console.log(err+" , "+ client);
});
The issue seems to be related to async/await. You cannot have awaitwithoutasync`.
Apart from this, you will not get _mongoClient outside of callback. You can access the client only inside the callback.
MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions, (err, client) => {
if(err) console.error(err);
else console.log(client);
});
or skip callback to get a promise
const _mongoClient = await MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions);
or
MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions).then(_mongoClient => {
console.log(_mongoClient)
}).catch(error => {
console.log(error)
});

Why bodyParser returns undefined?

I can't get body of request for the POST http://127.0.0.1:3001/users?name=Slava.
Server responce 'name is required'. Method getUsers work correctly. RethinkDB works good, server.js works too. I searched for similar answers here, but there is nothing suitable. There are very old answers, but they are not relevant.
This is request: http://127.0.0.1:3001/users?name=bob (I use Postman for POST)
Why bodyParser don't work in my code? I have no idea why this happens.
const Koa = require('koa')
const logger = require('koa-morgan')
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')
const r = require('rethinkdb')
const server = new Koa()
const router = new Router()
const db = async() => {
const connection = await r.connect({
host: 'localhost',
port: '28015',
db: 'getteamDB'
})
return connection;
}
server.use(bodyParser());
const insertUser = async(ctx, next) => {
await next()
// Get the db connection.
const connection = await db()
// Throw the error if the table does not exist.
var exists = await r.tableList().contains('users').run(connection)
if (exists === false) {
ctx.throw(500, 'users table does not exist')
}
let body = ctx.request.body || {}
console.log(body);
// Throw the error if no name.
if (body.name === undefined) {
ctx.throw(400, 'name is required')
}
// Throw the error if no email.
if (body.email === undefined) {
ctx.throw(400, 'email is required')
}
let document = {
name: body.name,
email: body.email
}
var result = await r.table('users')
.insert(document, {returnChanges: true})
.run(connection)
ctx.body = result
}
router
.post('/users', insertUser)
server
.use(router.routes())
.use(router.allowedMethods())
.use(logger('tiny')).listen(3001)
Body parser is used to parse POST requests (for POST body), here you have to use req.query instead of req.body, follow up this question.

Resources