What is the process of starting a mongoDB instance within a JavaScript class?

I have a DB class that is built with a mongoDB connection, but I am uncertain about how to initiate a db instance within this setup.

import mongo from 'mongodb'
import Grid from 'gridfs-stream'

export default class Db {
  constructor () {
    this.connection = new mongo.Db('db', new mongo.Server('127.0.0.1', 27017))
  }

  async dropDB () {
    const Users = this.connection.collection('users')
    await Users.remove({})
  }
}

In what way can I utilize this in my class?

db.open(function (err) {
  if (err) return handleError(err);
  var gfs = Grid(db, mongo);
})

Answer №1

The choice of approach would heavily depend on the desired style, but a potential implementation could look something like this:

const { promisify } = require('util');

export default class Database {
    constructor (url) {
            this.url = url || DEFAULT_DATABASE_URL;
            this.db = null;
            this.gfs = null;
            this.connection = new mongo.Db('db', new mongo.Server('127.0.0.1', 27017));
            
            // This part is untested but theoretically should function correctly
            this.connection.open = promisify(this.connection.open);
            this.connected = false;

            return this;
      }

    async connect(message) {
            let self = this;
            if(!this.db){
                try {
                    await self.connection.open();
                    self.gfs = Grid(self.connection, mongo);                 
                    this.connected = true;
                } catch (error){
                    log.info('Error connecting to MongoDB');
                }
            }
            return this;
        }

        isConnected() {
            return this.connected;
        }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the step-by-step process for updating a value within a MongoDB document

I have a MongoDB document that needs updating in the 'value' field based on a specific attribute. Here is the structure of the document: { "id": "64ca0aaa731a2a7284c24c57", "sections": [ { "id" ...

Error parsing Jquery ajax request for MongoDB _id field

Encountering a peculiar parser error (parsererror) while trying to access a JSON response from a MongoDB document. One document returns a mysterious parsererror: {"data":{"first_name":"Ray","last_name":"Reinger","_id":4e9c0ed27763dfba37000001}} Another ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Is the use of div:after content really affecting the width? I am having trouble getting my transition to work

Here is a simple code snippet that represents my actual code: #myDiv { background: black; color:white; float:left; min-width:45px; max-width:450px; -webkit-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #myDiv:hover:after { width ...

Incorporate server-side tags into client-side HTML and JavaScript scripts without the use of template engines

My goal is to carry out the following operation within client-side JavaScript from a file served using Node and Express: var rootURL = <%= "someurlfromserverconfig" %>; I am solely hosting a web directory from my Node app without any template engin ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

The WebDriverIO browser.Click function encountered difficulty locating an element while using Chrome, but it is functioning properly on Firefox

Currently, I am utilizing WebdriverIO in combination with CucumberJS for testing purposes. The following code functions correctly in Firefox; however, I encounter errors in Chrome which display element is not clickable. I am seeking a solution using JavaSc ...

"Integrating auto-expandable rows and subrows into a React table with the use

Presented here is my code for a React table using hooks. I encountered a challenge when trying to set all rows and subrows to be expanded by default upon opening the page. Despite attempting various solutions, none of them proved successful. Check out the ...

Creating a Sequence Generator in MongoDB

Within our domain model, we focus on handling sales invoices, each of which is assigned a unique number that is generated automatically. The process involves the SalesInvoiceService acquiring a number from the SalesInvoiceNumberGenerator, which is then use ...

Retrieving information from a datatable in vb.net with an array

Working on a chart using highcharts with code behind in vb.net... I have a datatable structured like this: Date - speed - data 2011 10k 6 2011 18k 7 2012 20k 10 2012 10k 2 2013 14k 4 2013 20k 6 Previously, to ...

What is the method for including an input field beside the y-axis label in Chart.js?

I'm struggling to implement a live poll using Chart.js where users can select their option by checking a checkbox next to the y-axis label. My initial attempt was unsuccessful as placing the input boxes outside of the canvas led to alignment issues wi ...

Utilizing $location.search parameters with ng-href for navigation

Something really strange is happening in my code right now. I'm utilizing ng-repeat to generate multiple elements based on an array of objects, like so: <a ng-repeat="report in reports" ng-href="#/report?report={{report.id}}+file=0" ></a> ...

Using Puppeteer to send messages on Discord without the use of a bot or application

Currently, I am coding a Puppeteer script to automate actions on Discord Web. Specifically, I need the script to open Discord Web, log in (including manual captcha and authorization steps), navigate to a channel, enter a message into the chat input field, ...

Do Typescript code require the use of a constructor?

After initializing a fresh Aurelia project using the aurelia-cli and executing the au new command, I received the following app.ts: export class App { message = 'Hello World!'; } To enhance my app.ts, I replaced it with the code from a helpfu ...

What is the best way to modify the nested state of a dynamically generated state with the useState hook?

I'm currently facing a challenge when trying to update a nested property of a useState object. Here's the specific scenario: In the component, there is a prop "order" that contains multiple items (line_items) which represent the products in th ...

JS seems to kick in only after a couple of page refreshes

I'm facing an issue with my 3 columns that should have equal heights. I've implemented some JavaScript to achieve this, which you can see in action through the DEMO link below. <script> $(document).foundation(); </script> <scri ...

What is the best method for incorporating a Vue 2 component into an HTML single file that relies on Vue 3's UMD build?

Exploring the utilization of (an intricate multi-select component with nested options) in a standalone Vue 3 single local HTML file, without relying on the Vue CLI for this specific task. When using the UMD build for Vue 2, it functions as outlined below ...

Executing the JavaScript function only a single time is what you're looking

I'm having trouble getting this script to work correctly on my website. It is supposed to trigger an alert when the specified id is in the viewport, but the issue I am encountering is that the alert keeps popping up repeatedly while the id is still vi ...

The integration of a side panel with a chrome extension is experiencing issues

I am working on a chrome extension with the following functionalities - Extract URL path from a specific webpage. (The webpage's URL remains constant) Open this URL in a new tab. It can be either http:// or https://. Embed an iframe containing a sim ...

Encountering issues with Windows 8 PhoneGap FileTransfer when trying to transfer text files

I'm facing an issue while attempting to upload a file to a server - the process seems successful, but the file doesn't actually transfer. I've temporarily hard-coded some values, but here's the code snippet: var options = new FileUplo ...