skip to Main Content

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


  1. I guess you didn’t mention the collection name of your MongoDB database in your URI.

    const uri = "mongodb+srv://<user>:<password>@bussar.v5r4pfd.mongodb.net/Bussar?retryWrites=true&w=majority/your_collection_name";
    
    Login or Signup to reply.
  2. Hi there you did not insert your db name:

    Add your db at the <dbname> place after mongodb.net/

    "mongodb+srv://<user>:<password>[email protected]/<DbName>?retryWrites=true&w=majority";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search