How to connect to mongodb with authorization in meanjs? - mongodb

I'm new to meanjs.
My problem is: my local mongodb has username/password, and I can't run meanjs demo successfully.
I git clone https://github.com/Azure-Samples/meanjs.git
And try to run it(npm run on Windows 10), but got this error:
Could not connect to MongoDB!
{ MongoError: Authentication failed.
at Function.MongoError.create (D:\Cordova\AzureMeanDemo\meanjs\node_modules\mongoose\node_modules\mongodb-core\lib\error.js:31:11)
then I set username/password in meanjs\config\env\development.js like:
db: {
uri: process.env.MONGOHQ_URL || process.env.MONGODB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
options: {
user: 'superAdmin', //here
pass: '*****' //here
},
// Enable mongoose debug mode
debug: process.env.MONGODB_DEBUG || false
},
...
but I still got the same error.
I've searched on google for a whole day, but got nothing about this.
Could anyone help me on this problem?
-------------- Solved -------------------
I changed uri: 'mongodb://username:passwd#localhost/mean-dev?authSource=adm‌​in'. It worked for me.

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/projectName,{user:'',pass:''});

Related

MongoDB Atlas + prisma + nextjs error: Error validating datasource `db`: the URL must start with the protocol `mongo`

can't connect to mongodb server on atlas when using env var in mongodb + prisma + nextjs application. getting this error error: Error validating datasource db: the URL must start with the protocol mongo. However if I just put the connection string directly into url rather than doing env("DATABASE_URL"), then it works.
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
.env: DATABASE_URL=mongodb+srv://username:password#somemongodbserver/mydb?retryWrites=true&w=majority
.env.local: DATABASE_URL=mongodb+srv://username:password#somemongodbserver/mydb?retryWrites=true&w=majority
Also tried putting this in next.config.js
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
env: {
DATABASE_URL: process.env.DATABASE_URL,
},
};
turns out I already I had DATABASE_URL env var set locally for Postgres and it was being used, changing the env var name in the nextjs app fixed the issue

Deno Uncaught Error: No such host is known. (os error 11001)

I tried to connect the MongoDB Atlas to my Deno Application using https://deno.land/x/mongo#v0.21.2 framework. I tried the below code to run my application. but I get an error No such host is known. (os error 11001) What went wrong here
Error
error: Uncaught Error: No such host is known. (os error 11001)
at unwrapResponse (rt\10_dispatch_json.js:24:13)
at sendAsync (rt\10_dispatch_json.js:75:12)
at async Object.connect (rt\30_net.js:221:13)
at async MongoClient.connect (client.ts:41:14)
at async mongodb.ts:33:1
Mongodb.ts File
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client1.connect("mongodb+srv://user1:MYPASSWORD#cluster0.hmdnu.mongodb.net/TestingDB?retryWrites=true&w=majority");
const db = client1.database("TestingDB");
export default db;
I used this command to run my server
deno run --allow-net --allow-write --allow-read --allow-plugin --unstable server.ts
I fixed this using https://www.youtube.com/watch?v=hhdhydffKKE this video reference
Follow these steps to fix this
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client.connect({
db: "<db>",
tls: true,
servers: [
{
host: "<host>",
port: 27017,
},
],
credential: {
username: "<user>",
password: "<password>",
db: "<db>",
mechanism: "SCRAM-SHA-1",
},
});
const db = client1.database("TestingDB");
export default db;
This is not mentions in the document, but this will help to fix the issue
<db> is the database name, you can get the database name by following these steps
Step-1
Step-2
To find the <host> follow these steps
Step -1
Step -2
Step -3

Unknown auth message code 1397113172 when connect to Heroku postgres

Thanks reading my issue.
Currently, I am using postgres (hobby-dev) on Heroku and facing this issue every time that I connect to the database.
error: Uncaught (in promise) Error: Unknown auth message code 1397113172
throw new Error(`Unknown auth message code ${code}`);
^
at Connection.handleAuth (connection.ts:197:15)
at Connection.startup (connection.ts:155:16)
at async Pool._createConnection (pool.ts:32:5)
at async pool.ts:61:7
at async Promise.all (index 0)
at async Pool._startup (pool.ts:63:25)
My application using Deno now
import { Pool } from "https://deno.land/x/postgres/mod.ts";
import { config } from "./config.ts";
const port = config.DB_PORT ? parseInt(config.DB_PORT || "") : undefined;
const POOL_CONNECTIONS = 20;
const dbPool = new Pool({
port,
hostname: config.DB_HOST,
user: config.DB_USER,
database: config.DB_NAME,
password: config.DB_PASS
}, POOL_CONNECTIONS);
export { dbPool };
Here is debug screen.
I have found this issue post and it mentioned about lacking ssl. Not sure how to do it on heroku.
I have tried some solutions, even change lib to pg and it still not work. I am very appreciated if any clue or help to fix this issue.
Note:
I read a document on heroku about "Heroku Postgres Connection Pooling is not available for Hobby-tier databases.". Then I switched to use Client with syntax similar like this to connect to Heroku postgres this:
import { Client } from "https://deno.land/x/postgres/mod.ts";
let config;
config = {
hostname: "localhost",
port: 5432,
user: "user",
database: "test",
applicationName: "my_custom_app"
};
// alternatively
config = "postgres://user#localhost:5432/test?application_name=my_custom_app";
const client = new Client(config);
await client.connect();
await client.end();
ref: https://deno-postgres.com/#/

Unable to connect to postgres using deno.js

Unable to connect to postgres in deno.js.
Here is the configuration:
const dbCreds = {
applicationName: "appname",
user: "user_sfhjwre",
database: "d9iu8mve7nen",
password: "68790f31eelkhlashdlkagsvADSDa52f9d8faed894c037ef6f9c9f09885603",
hostname: "ec2-345-34-97-212.eu-east-1.xx.amazonaws.com",
port: 5432,
};
export { dbCreds };
Usage:
import { Client } from "https://deno.land/x/postgres/mod.ts";
import { dbCreds } from "../config.ts";
const client = new Client(dbCreds);
await client.connect();
Also tried:
config = "postgres://user#localhost:5432/test?application_name=my_custom_app";
const client = new Client(config);
await client.connect();
Same result:
Uncaught Error: Unknown auth message code 1397113172
Is there anything wrong with the syntax, I can connect to the same db using prisma.
I have the PostgreSQL server in a remote server and, each time my public IP changes, I need to change the pg_hba.conf in order to set my new public IP as authorized for remote access.
Hope this helps.
Best regards.

Mocha tests can't connect to postgres database, using knex

I am trying to implement some integration tests using mocha for functions that interact with a postgres database through knex, in a nodejs express app.
The functions work outside of mocha - I can start the app in node or nodemon, submit requests through Postman, retrieve records from the database, add new records, etc. But when I try to test the code through mocha, I get errors like the following for any functions that try to access the database:
select * from "item" where "user_id" = $1 - relation "item" does not exist
The environment variable for the database connection is set to connect to the right database; when I manually test the app end-to-end, everything works; I get data back from the database.
I've included what I think are the relevant code snippets below: the test script for one of the tests that won't work, the function I'm trying to test, and the modules that that function relies on.
TEST SCRIPT
const Item = require('../db/item');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
// set up the middleware
chai.use(chaiAsPromised);
var should = require('chai').should()
describe('Item.getByUser', function() {
contex`enter code here`t('With valid id', function() {
const item_id = 1;
const expectedResult = "Canoe";
it('should return items', function() {
return Item
.getByUser(item_id)
.then(items => {
items[0].name.should.equal(expectedResult);
});
});
});
SNIPPET FROM THE ITEM.GETBYUSER FUNCTION:
const knex = require('./connection');
module.exports = {
getByUser: function(id) {
return knex('item').where('user_id', id);
},
SNIPPET FROM THE CONNECTION MODULE:
require('dotenv-safe').config();
const environment = process.env.NODE_ENV || 'development';
const config = require('../knexfile')[environment];
module.exports = require('knex')(config);
SNIPPET FROM THE KNEXFILE MODULE:
module.exports = {
development: {
client: 'pg',
connection: process.env.DATABASE_URL
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL
}
};
The error message I get for the above test is:
1) Item.getByUser
With valid id
should return items:
select * from "item" where "user_id" = $1 - relation "item" does not exist
error: relation "item" does not exist
at Connection.parseE (node_modules\pg\lib\connection.js:567:11)
at Connection.parseMessage (node_modules\pg\lib\connection.js:391:17)
at Socket.<anonymous> (node_modules\pg\lib\connection.js:129:22)
at addChunk (_stream_readable.js:284:12)
at readableAddChunk (_stream_readable.js:265:11)
at Socket.Readable.push (_stream_readable.js:220:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
Okay, it's looking like this was in fact related to the environment variable for the database in some way I can't quite figure out. Although I had the database connection set to 'postgres://localhost/mydatabase' the database actually being used when I tested the db live, including migrating and seeding the database through knex commands, was 'postgres://localhost/username' - a database with the same name as the Owner of 'mydatabase'. But I think the mocha tests were trying to connect to mydatabase, which was still empty at that point, since the migrate and seed affected the the database 'username.'
So, I think this can be closed. I'll try to replicate the problem where I was connected to the wrong db; not sure how that could have happened, as I never intentionally set the connection, or any environment variable to 'postgres://localhost/username'.