Home > database >  error connecting to mongodb due to {useNewUrlParser:boolean, useUnifiedTopology:boolean} is not assi
error connecting to mongodb due to {useNewUrlParser:boolean, useUnifiedTopology:boolean} is not assi

Time:12-31

Below is the code I am using to connect to mongodb.

import { MongoClient } from "mongodb"

const user = 'user_001'
const userPassword = '<password>'
const cluster = 'cluster0.1jjgj'

const url = `mongodb srv://${user}:${userPassword}@${cluster}.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`

export const connectDatabase = async() => {
  
  const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  const db = client.db('main')

  return {
    listings: db.collection('test-listings')
  }
}

Tried connecting mongodb with MongoDB NodeJS Driver mongodb but following error occurs. what does MongoClientOptions (useNewUrlParser: boolean, useUnifiedTopology:boolean) do in mongodb and what could be causing this error ? please explain. Thank you.

  Overload 1 of 4, '(url: string, callback: Callback<MongoClient>): void', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'Callback<MongoClient>'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'Callback<MongoClient>'.
  Overload 2 of 4, '(url: string, options: MongoClientOptions): Promise<MongoClient>', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'MongoClientOptions'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'MongoClientOptions'.ts(2769)

CodePudding user response:

You should be able to connect to the client with:

export const connectDatabase = async () => {
    const client = new MongoClient(url);
    await client.connect();
    const db = client.db('main');
  
    return {
      listings: db.collection('test-listings'),
    };
  };

CodePudding user response:

This works perfectly fine, Emphasis on poolSize.

mongoose.connect(
dbUrl,
{
useNewUrlParser: true,
useCreateIndex: true,
autoIndex: true,
useUnifiedTopology: true,
poolSize: 10,
},
function (err) {
  if (err) {
    console.log(`Unable to Connect to Database. ${err.name} ${err.message}`);
    process.exit(1);
   } else {
    console.log(new Date());
    console.error("Successfully connected to Database");
   }
  }
);

for more info check https://www.mongodb.com/community/forums/t/argument-of-type-usenewurlparser-boolean-useunifiedtopology-boolean-is-not-assignable-to-parameter-of-type/119731/4

  • Related