I've recently joined to a project that uses Mongodb. I'm a newbie to this database. I need to find the database credentials to get an export of it (as a backup) before everything.
The doc says, the connect() method would have these parameters:
connect(url, user, password)
But I don't see that syntax in the real project. Here is the content of mongoose.js file:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(
'mongodb://bpAdmin:Bp1400##32.150.189.207:27017/bpDB?authSource=admin',
{
useCreateIndex: true,
useFindAndModify: true,
useNewUrlParser: true,
useUnifiedTopology: true,
autoIndex: true,
}
);
mongoose.set('useCreateIndex', true);
module.exports = {
mongoose,
};
(The IP and some other names just changed because of some security reasons)
Could you please tell me what's the user and password and db name?
Check out the format in offical documentation on connection string,
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
So for your questions,
info
value
username
bpAdmin
password
Bp1400#
db name used for auth
admin
default db to connect to
bpDB
Related
while trying to connect with my mongoDB atlas using mongoose connect method in node js I'm getting below mentioned parser error, I've checked my DB credentials and there are no special characters (:, /, ?, #, [], #) present in it.
Error:
MongoParseError: URI malformed, cannot be parsed
Code:
const mongoose = require('mongoose');
const DB = process.env.DB.replace('<password>', process.env.DB_PASSWORD);
mongoose
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connections);
console.log('DB connection successful!');
});
So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.
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;
(node:8041) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
With connect function:
mongoose.connect('mongodb://localhost:27017/DATABASE', { useUnifiedTopology: true }});
With MongoClient:
var mongoclient = new MongoClient(new Server("localhost", 27017), { useUnifiedTopology: true });
Simply send options object to second parameter.
I have a node.js application that is deployed to azure using CosmosDB and the MongoDB API. My application uses mongoose which works seamlessly in 4.13.9.
My application that works connects as follows:
var configDB = require('./config/database');
var mongoose = require('mongoose');
mongoose.connect(configDB.url, { useMongoClient: true } );
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
the config/database file is defined as follows (changed username, password, DB to protect the innocent):
module.exports = {
'url': 'mongodb://azureusername:azurepassword#myazuredb.documents.azure.com:10255/?ssl=true'
}
Now the problem comes when I install mongoose 5.0.1. I remove the useMongoClient option from the connect and got rid of the promise so my connect code is now:
mongoose.connect(configDB.url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
When this runs I get the following in the console:
(node:21392) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 2): Error: Password contains an illegal
unescaped character
I can even comment out the connection code to where it is only the mongoose.connect and that is what is giving the error. What am I doing wrong? Is there a breaking change in 5.0.1 that I need to account for? As a side note that may or may not be related, I saw some notes about now giving a callback instead of using promises so if someone has an example of how they do that in a Node/Express app that would be great, but it doesn't seem like that's the isee when I'm getting an error reported on the connect about an illegal character.
NOTE: The config file is exactly the same when running against 4.13.9 or 5.0.1 so I know the password is valid and it is not the issue.
For the latest version (v5.0.1) of Mongoose, you'll need to use this syntax to connect to MongoDB like this:
const mongoose = require('mongoose');
mongoose.connect('mongodb://<cosmosdb-username>.documents.azure.com:10255/<databasename>?ssl=true', {
auth: {
user: '<cosmosdb-username>',
password: '<cosmosdb-password>'
}
})
.then(() => console.log('connection successful'))
.catch((err) => console.error(err));
The password for the Azure Cosmos DB instance I got ended with ==, hence the illegal characters message. These characters must be urlencoded.
An equals sign = urlencoded is %3D.
A properly encoded connection string for the password jitsu== could look like mongodb://user:jitsu%3D%3D#localhost:27017/dbname?ssl=false.
Also be aware that the connection strings you get from the Cosmos DB blade in the Azure Portal doesn't include the database name.
To connect to local cosmos db emulator use the following connection method (for mongoose > 5.0.0):
mongoose.connect(
`mongodb://localhost:10255/?ssl=true`,
{
auth: {
user: "localhost",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
dbName: "admin"
}
}
);
Or you may also do the following:
const encodedPassword = encodeURIComponent("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
mongoose.connect(`mongodb://localhost:${encodedPassword}#localhost:10255/admin?ssl=true`);
Connection string has following format:
mongodb://username:password#host:port/[database]?ssl=true
and there seems to be some issue with default password character escaping. Thus we encoded it separately.
Add the new url parser as an option { useNewUrlParser: true }
Change you line 3 to:
mongoose.connect(configDB.url, { useMongoClient: true, useNewUrlParser: true } );