Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.92k stars 3.84k forks source link

throw new MongooseError('The `uri` parameter to `openUri()` must be a string) #8242

Closed its-me-ilia closed 4 years ago

its-me-ilia commented 5 years ago

i just configured my new project and added mongoose and as it seems new release 5.7.4 has a bug in it because of when i use code like this:

require('dotenv').config({
     path: '../.env' 
})
const mongoose = require('mongoose');
console.log(process.env.MONGO_URI)
mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useCreateIndex:true,
    useFindAndModify: false,
    useUnifiedTopology: true
 })
 .then(()=>{
    console.log('con to db established')
 })
 .catch(err=>{
    console.log(`db err: ${err.message}`);
    process.exit(-1)
 }) 
 const schemas = require('./schemas');
 const models = {};
 for(let i in schemas){
    models[i] = mongoose.model(i, schemas[i]); 
 }
 //exporting modules

it logs error in title even tough when i log process.env.MONGO_URI it logs correct value and when i add url straight into mongo.connect() like this "mongodb+srv://MYUSERNAME:MYPASSWORD@<CLUSTER>.mongodb.net/MYDBNAME?retryWrites=true&w=majority" it still logs same, how can i fix it? i am saying that is is 5.7.4 release bug because i have other project initialized with mongo ^5.7.3 and it is not logging this + i have this code in that project for generating models and connection

vkarpov15 commented 5 years ago

The error message logged should be 'The uri parameter to openUri() must be a string, string, got "TYPE"' where 'TYPE' is the type it got. Can you please paste the full error message?

blocsaga commented 4 years ago

Hi i have a error like this. When i use direct connection then there is no error but when using routing then like this below---

C:\Users\John Bhandari\Desktop\CMS tutorial\node_modules\mongoose\lib\connection.js:579 throw new MongooseError('The uri parameter to openUri() must be a ' + ^ MongooseError: The uri parameter to openUri() must be a string, got "object". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

My code in app.js is like this --> const mongoDbUrl= require("./config/configuration");

mongoose.connect(mongoDbUrl, {useNewUrlParser: true, useUnifiedTopology:true});
mongoose.connection.once('open', function(){
  console.log('Conection has been made!');
}).on('error', function(error){
    console.log('Error is: ', error);
});
nts6 commented 4 years ago

@fktmjohn1 Having the same issue let me know if you find the solution

blocsaga commented 4 years ago

I explored but couldn't i am trying i hope i will find it soon and get it posted. Thanks

nts6 commented 4 years ago

I am now getting a depreciation warning

On Sun, Feb 23, 2020, 10:57 PM Ron Miller notifications@github.com wrote:

I explored but couldn't i am trying i hope i will find it soon and get it posted. Thanks

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/Automattic/mongoose/issues/8242?email_source=notifications&email_token=AOUOBNSSIC2754Y26GKLNS3RENAUBA5CNFSM4JAEAVT2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEMWSAFI#issuecomment-590159893, or unsubscribe https://github.com/notifications/unsubscribe-auth/AOUOBNS4DOEZCBRXDDV7K6DRENAUBANCNFSM4JAEAVTQ .

nts6 commented 4 years ago

@fktmjohn1 surprisingly I solve the error on my end let me know if your still having issues even thou we might be working on completely different projects.

blakelower commented 4 years ago

@nts6 how did you solve the error?

blocsaga commented 4 years ago

Could you please write your code here. I am still having the same issue.

blakelower commented 4 years ago

This is the issue that I am now getting, Ive been in contact with MongoDB Atlas, but theyre support is not helpful for this really.

(node:20777) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connection <monitor> to 35.223.86.252:27017 closed at new MongooseServerSelectionError (/Users/test/Desktop/full-stack/mern/backend/node_modules/mongoose/lib/error/serverSelection.js:22:11) at NativeConnection.Connection.openUri (/Users/test/Desktop/full-stack/mern/backend/node_modules/mongoose/lib/connection.js:808:32) at Mongoose.connect (/Users/test/Desktop/full-stack/mern/backend/node_modules/mongoose/lib/index.js:333:15) at Object.<anonymous> (/Users/test/Desktop/full-stack/mern/backend/server.js:14:10) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3) (node:20777) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:20777) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

blocsaga commented 4 years ago

I think you should mention promise like this {useNewUrlParser:true, useUnifiedTopology:true} or your URI mistake.

blakelower commented 4 years ago

I did do that. But im still learning too. This is my server.js page `const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose');

require('dotenv').config();

const app = express(); const port = process.env.PORT || 5000;

app.use(cors()); app.use(express.json());

const uri = process.env.ATLAS_URI; mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true } ); const connection = mongoose.connection; connection.once('open', () => { console.log("MongoDB database connection established successfully"); })`

and my .env page: ATLAS_URI=mongodb+srv://blakelower:<password>@cluster0-wnpwi.gcp.mongodb.net/test?retryWrites=true&w=majority

super new to this and fully aware of the password not being shown and i have a port

blocsaga commented 4 years ago

ATLAS_URI=mongodb+srv://blakelower:@cluster0-wnpwi.gcp.mongodb.net/test?retryWrites=true&w=majority i think the problem is in your uri //have you put password without bracket and simply your DB User password?

blakelower commented 4 years ago

i have :/

blakelower commented 4 years ago

Would anyone on here have an idea?

nos-nart commented 4 years ago

I ran into the same error. Is there anyone has fixed it yet?

mehditaga commented 4 years ago

Check the IP address you choose in mongoDB. Maybe the problem is on this side ?

AAbutayli commented 4 years ago

I have the same issue.. checked IP Whitelist and added my current IP (was different from the previous one surprisingly), but now I'm getting:

Error: queryTxt ETIMEOUT cluster0-p701o.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19) { errno: 'ETIMEOUT', code: 'ETIMEOUT', syscall: 'queryTxt', hostname: 'cluster0-p701o.mongodb.net' }

(node:73849) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-p701o.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19)

(node:73849) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

(node:73849) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

AAbutayli commented 4 years ago

It turned out that I was using a VPN and it caused all the mess..

akiosTerr commented 4 years ago

I'm having the same problem, what really bothers me is that the console shows NO errors, it says the database connection is established, the only way to see the error is entering debug mode on VS code.

I only entered debug mode because my routing middleware wasn't working at all I figured to be an express error, but now I saw this mongoose error I am not so sure.

here is my server code:

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const usersRouter = require('./routes/users');

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true
});
const connection = mongoose.connection;
connection
    .once('open', () => {
        console.log('mongoDB database connection established');
    })
    .on('error', err => {
        console.log('Error: ', err);
    });

app.use('./users', usersRouter);

app.get('/', (req, res) => {
    res.send('Hello FUCKIN WORLD');
});

app.listen(port, () => {
    console.log(`server is running on port: ${port}`);
});

and my user Router:

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((req, res) => {
    User.find()
        .then(users => res.json(users))
        .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {
    const username = req.body.username;
    const newUser = new User({ username });
    console.log('add route initiated!');

    newUser
        .save()
        .then(() => res.json('User added!'))
        .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

PLEASE HELP