0

I've tried to develop a server with nodejs that is link with NOSQL DB, in particular I've developped it with MONGODB. I'm not sure I manage to connect it well due to the fact if I run the code below it should return the id of the element inserted but it prints in output a blank, in the case I substitute the async with a normal development it return the following error " MongoError: Topology is closed, please connect " .I've tried to use the lines of code with /the comment below the code/ but it returns another error.

I think I don't connect well mongodb with my server but I don't know I follow the commands deliver in mongodb step by step.(create a cluster(free),create a user,create a db and then a collection and then connect use the information set before.)

I said it because I refresh the cluster on mongodb but I don't obtain any change

    const MongoClient = require('mongodb').MongoClient;
    const password = encodeURIComponent('22');
    const user=encodeURIComponent('id');
    const dbs = encodeURIComponent('users');
    const uri = "mongodb+srv://${user}:${password}@cluster/${dbs}?retryWrites=true&w=majority";
    const client = new MongoClient(uri, { useNewUrlParser: true ,useUnifiedTopology:true,  connectTimeoutMS: 30000 ,  keepAlive: 1});

(async()=>{




await client.connect();
const databse=client.db("users");
const collection=databse.collection("readers");

const result= await collection.insertOne( {

    "name":"Chocolate",
    "ingredients":[
        "eggs","chocolates"
    ]
});
console.log(result.insertedId);
//client.close();
});
/*
   client.connect(err => {
   const collection2 = client.db("users").collection("readers");
   // perform actions on the collection object

   var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };  
   collection2.insertOne(myobj, function(err, res) {  
   if (err) throw err;  
   console.log("1 record inserted");
   //client.close();
   });
   });
   */

1 Answer 1

2

I see a few problems with the code.

  1. There is no reason for you to use encodeURIComponent with static strings. But hopefully, that's just a placeholder for some real credentials that are going to come from an environment variable.

  2. The variable uri is being assigned with a static string that contains a templating pattern, but it is using double quotes instead of backticks, so it won't interpolate the variables, which in turn will generate an invalid connection string.

  3. The same variable uri, after having replaced the double quotes " with the backticks ` might still not work because of the strange hostname "cluster" that should come from some sort of settings of env var as well.

  4. The code seems to have the intent of using an Immediately Invoked Function Expression (IIFE for short) but it is in fact not even calling the function because the parenthesis pair is missing after the function block.

Assuming your credentials are correct the updated code below should do the trick for you:

const MongoClient = require('mongodb').MongoClient
const password = encodeURIComponent('22')
const user = encodeURIComponent('id')
const dbName = encodeURIComponent('users')
const host = process.env.MONGO_HOST || 'localhost' // or whatever is the hostname you want
const uri = `mongodb+srv://${user}:${password}@${host}/${dbName}?retryWrites=true&w=majority`

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, connectTimeoutMS: 30000, keepAlive: 1 })

;(async () => {
  await client.connect()
  const databse = client.db('users')
  const collection = databse.collection('readers')

  const doc = {
    name: 'Chocolate',
    ingredients: [
      'eggs', 'chocolates'
    ]
  }

  const result = await collection.insertOne(doc)
  console.log({ result })
  console.log(result.insertedId)
  client.close()
})()
Sign up to request clarification or add additional context in comments.

4 Comments

The following code return the following problem: (node:7896) UnhandledPromiseRejectionWarning: MongoParseError: URI does not have hostname, domain name and tld (node:2700) 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() (node:2700) [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
You have to make sure the generated content of the uri variable is valid. You can try to console.log({uri}) right after it gets created then you can try to use the very same connection string with a local MongoDB client. Until you are 100% sure that your connection string works you should not work on your code.
Thank you Mestre San you're focus on my real problem: the uri with some try I manage to understand which is the correct uri.
Now I manage to do that thanks a lot! the main problem was the host that was not corret and also the levl of the drive thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.