Muirik
Muirik

Reputation: 6289

Connecting to MongoDB Successfully, But Having Issues with `getCollection()`

I am writing some tests for a Node/Mongo project, and in one of my tests I need to connect to the database, and then pull a document from my jobs collection. However, I am running into an issue. I can connect to the database successfully, but then get an error on my findOne(). The specific error is:

TypeError: db.getCollection is not a function

Here is the code:

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'sample_db';

// Create a new MongoClient
const client = new MongoClient(url);

client.connect(async function (err) {
  assert.equal(null, err);
  console.log("Connected successfully to server"); // I see this in the console

  const db = await client.db(dbName);

  let savedJobResult = await db.getCollection("jobs").findOne({
    "name": "Agenda Job Test"
  });

  console.log('savedJobResult: ', savedJobResult);

  client.close();
});

What am I missing here?

Upvotes: 0

Views: 164

Answers (2)

Mahesh Bhatnagar
Mahesh Bhatnagar

Reputation: 1080

Try this query

  let savedJobResult = await db.collection("jobs").findOne({
    "name": "Agenda Job Test"
  });

Upvotes: 1

Yuri Khomyakov
Yuri Khomyakov

Reputation: 380

change getCollection to collection

const insertDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Insert some documents
  collection.insertMany([
    {a : 1}, {a : 2}, {a : 3}
  ], function(err, result) {
    assert.equal(err, null);
    assert.equal(3, result.result.n);
    assert.equal(3, result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
}

Upvotes: 0

Related Questions