Executing multiple commits within a single MongoDb connection

I'm working on developing a JavaScript application to be executed locally with Node.js. The goal is to allow users to input commands that will manipulate data in a MongoDb connection.

The challenge lies in keeping the MongoDb connection open while Node.js runs, ensuring that user commands are executed as intended.

I've tried using multiple connections but encountered issues with the promise stack. For instance, when a user inserts an object and then tries to delete it afterward, nothing happens.

const MongoClient = require('mongodb').MongoClient;
const uri = require('./mongoConnection.json'); // contains connection info
const mongoClient = new MongoClient(uri.connectionString, { useNewUrlParser: true });
mongoClient.connect(function(err, db){
    var dbo = db.db("TestBotDb").collection("Test");
    dbo.insertOne({ "data1" : "new data", "data2" : "new data2" });    

    var result = dbo.findOne({ "data2" : "new data2" });
    dbo.deleteOne({ "_id" : result._id});

});

Due to delay in insertions, I'm unsure how to structure this into functions for future use. Waiting for an insertion before attempting deletion while the application runs isn't ideal since I can't predict when a user might choose to insert or delete.

Answer №1

If you want to achieve this, you can utilize async/await in your code.

const MongoClient = require('mongodb').MongoClient;
const uri = require('./mongoConnection.json'); // storing connection information
const mongoClient = new MongoClient(uri.connectionString, { useNewUrlParser: true });

mongoClient.connect(async (err, db) =>{
    var dbo = db.db("TestBotDb").collection("Test");

    // Inserting data and waiting for the operation to complete or encounter an error
    await dbo.insertOne({ "data1" : "new data", "data2" : "new data2" });

    // Retrieving data and waiting for the operation to complete or encounter an error
    var result = await dbo.findOne({ "data2" : "new data2" });

    // Deleting data and waiting for the operation to complete or encounter an error
    await dbo.deleteOne({ "_id" : result._id});
});

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

Having trouble with Jquery toggle functionality on Firefox browser

Can anyone help me troubleshoot this jQuery script that doesn't seem to be functioning properly in Firefox? $(document).ready(function () { $('#all_lists').hide(); $('#add_lists').click( function(){ event.stopPropagation ...

No data retrieved from MongoDB due to lack of results

Having an issue with fetching data from MongoDB using Node.js. Even though I believe the connection to the database is established and collections are accessible, I only receive an empty response. Below is my Server.js file: // set up =================== ...

A guide to gathering a variety of data types for an array in Node.js

As a JavaScript beginner, I am on a mission to enhance my skills by solving online judge problems. However, I have hit a roadblock with a specific issue. The problem requires me to take input from the user in the form of an integer and a string in one go, ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

Error with XMLHTTPRequest loading in beforeunload/unload event handlers in iOS 13.4.1 encountered

Currently, I am utilizing XMLHTTPRequest for data posting in JavaScript. Previously, it functioned smoothly on Safari and Chrome browsers up to iOS 13.3.1. However, upon updating to the latest OS version, iOS 13.4.1, an error message stating "XMLHTTPReques ...

Guide on executing protractor suites with various users

I have a config file that I usually use to execute a single user and multiple test suites. However, I am currently facing an issue where I need to run certain protractor suites with User A and other protractor test suites with User B. I am unsure of how to ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

When the 'shown' event is triggered by manually activating a Bootstrap modal

Issue arises when I attempt to display the modal for the first time. The modal appears, but the shown event is triggered only when I drag the modal or click on the close button (I can see the alert). I am working with Bootstrap 2.3.2 and Firefox 26.0. $ ...

The reactjs-toolbox radio button group remains unchanged

In my React application, I have implemented radio buttons using the following code: <RadioGroup name='steptype' className={css.ProcessStepRadioButtons} value={this.state.stepsData[stepNumber].stepType} onChang ...

Numerous data retrieval commands within the componentWillMount lifecycle method

Initially, I utilized the componentWillMount() method to populate the articles property successfully by iterating over the values to display various images/text. However, I am now encountering an issue as I also need to use componentWillMount to populate ...

Analyzing and sorting two sets of data in JavaScript

I am currently working with two arrays that are used to configure buttons. The first array dictates the number of buttons and their order: buttonGroups: [ 0, 2 ] The second array consists of objects that provide information about each button: buttons = ...

Assign characteristics to particular items within an array

When working with AngularJS/Javascript, I have an array of objects that each contain a date. My goal is to order these objects by date and then add an attribute to the last object that has a specific datetime. If there are two objects with the same date, t ...

Guide to customizing the sort arrow colors of b-table in Bootstrap 4 within Nuxt framework

https://i.sstatic.net/axVNu.png Using nuxt and bootstrap, I've noticed that the default sorting arrows in the table are too dark for my background. Is there a way to change the color of these sorting arrows? <b-table show-empty small ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...

onPropertyChange function exclusive to Internet Explorer

In Internet Explorer, the onPropertyChange event is functioning properly. I have utilized onPropertyChange to input text into one textbox and simultaneously display the same text in another textbox. Are there any alternate methods available to address this ...

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

Unfortunately, the rest operator is not compatible with webpack when using Babel

Currently in my app, I am utilizing webpack and React. However, I have encountered an issue where webpack does not seem to be accepting the syntax var {id, ...data} = pulse;. Error: ERROR in ./src/main.js Module build failed: SyntaxError: Unexpected toke ...

Properly removing an object from a THREE.js scene while still preserving it in the HEAP

Is there a correct way to remove mesh from a scene without causing memory leaks? removable_items = []; box = new THREE.Object3D(); scene.add(box); function add() { var mesh = new THREE.Mesh( new THREE.IcosahedronGeometry( 10, 5 ), ...

Is it possible to utilize JSON in Struts 2 to bypass the necessity of tags and page mappings?

Lately, I've been pondering the concept of a design approach that utilizes unmapped pure HTML and JavaScript pages pulling JSON data from Struts 2. This means no action mappings are required, resulting in relative page references with minimal need for ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...