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();
});
});
*/