I’m trying to connect to mongodb, and then insert a document called data
, I can see on my cluster that I connect, but no data gets inserted. I don’t get any errors either. Here’s my code:
const {MongoClient, ServerApiVersion} = require('mongodb');
const uri = "mongodb+srv://<user>:<password>[email protected]/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
MongoClient.connect(uri, { useNewUrlParser: true }).then((client) => {
let db = client.db("Bussar");
});
function createbus(data) {
client.connect(err => {
const bussar = db.collection("busscoll");
bussar.insertOne(data);
client.close()
});
}
I do have both user and password filled out in my uri.
EDIT
Alright, so I’ve updated my code, and I belive it works better than before. Although it still doesn’t insert anything, I added some checkpoints, and I only get to the first one. Code:
const {MongoClient, ServerApiVersion} = require('mongodb');
const uri = "mongodb+srv://<user>:<password>[email protected]/bussdb?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
function createbus(data) {
console.log("checkpoint 1");
try {
client.connect(err => {
console.log("checkpoint 2");
const db = client.db("bussdb")
console.log("checkpoint 3");
const bussar = db.collection("busscoll");
console.log("checkpoint 4");
bussar.insertOne(data, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log(result);
client.close();
});
console.log("checkpoint 5");
});
} catch (e) {
console.error(e);
} finally {
client.close();
}
}
2
Answers
I guess you didn’t mention the collection name of your MongoDB database in your URI.
Hi there you did not insert your db name:
Add your db at the
<dbname>
place aftermongodb.net/