Updating records in a MongoDB database using C# may seem challenging, but fear not as

This is the C# code I have written for updating a record in MongoDB:

public static void updateSubmit(string id,string fname,string lname,string email,string password,string address)
{
    string connectionString = "mongodb://10.10.32.125:27017";
       MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
       MongoClient mongoClient = new MongoClient(settings);
       var Server = mongoClient.GetDatabase("mongovaibhav");
       var collection = Server.GetCollection<employee>("mongov");
       ObjectId objectId = ObjectId.Parse(id);
       var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);
       employee emp = new employee();
       emp.fname = fname;
       emp.lname = lname;
       emp.email = email;
       emp.pass = password;
       emp.address = address;
       collection.ReplaceOneAsync(filter, emp);
}

Below is my Ajax code used for sending an update request along with data:

 function updateSubmit()
    {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'Home.aspx/updateSubmit',
            data: "{'id':'" + $("#hidden").val()+ "','fname':'" + $("#fname").val() + "','lname':'" + $("#lname").val() + "','email':'" + $("#email").val() + "','password':'" + $("#password").val() + "','address':'" + $("address").val() + "'}",
            async: false,
            success: function (response) {
                alert("You Have SuccessFully Update Data");
            },
            error: function () {
                console.log('there is some error');
            }
        });
    }

I am facing an issue where I receive the alert message indicating successful record update, but the changes are not reflected in the database.

Answer №1

After some troubleshooting, I discovered the solution to my issue. It turns out that I made a mistake in my "Param" variable where I typed Password instead of "pass", as my employee class actually contains a "pass" property. Thank you to everyone who helped me figure this out! @souvik @felix

string connectionString = "mongodb://10.10.32.125:27017";
            MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            MongoClient mongoClient = new MongoClient(settings);
            var Server = mongoClient.GetDatabase("mongovaibhav");
            var collection = Server.GetCollection<employee>("mongov");
            ObjectId objectId = ObjectId.Parse(id);
              var filter = Builders<employee>.Filter.Eq(s => s._id, objectId);   
            string param = "{$set: { fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "',pass:'" + password + "',address :'" + address + "' } }";
            BsonDocument document = BsonDocument.Parse(param);
            collection.UpdateMany(filter, document);

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

The server received a GET request instead of a DELETE request

Currently, I'm facing a challenge in writing the frontend of an application. My goal is to implement a DELETE method using AJAX, but when I execute the code, Spring seems to be triggering a GET request instead. Here's the snippet of my HTML code ...

Deselecting every row in the px-data-table

I have integrated px-data-table into my Angular2 application. The data-table setup in my code looks like this: <px-data-table #myTableRef [tableData]='tableDetails' language="en" (px-row-click)="selectedChanged($event)" (px-select-all-click)= ...

Focus on indexing the entire embedded documents

I am analyzing the structure of this document with the following content: { "_id": ObjectId("1234"), "name": "TestName", "location": { state: "NY", city: "New York" ,"geoid":28042}, "ts":<timestamp> .. .. }.. There is approximately 1 GB of ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

Transforming an ASP Web Form into a Custom User Control

Currently, I am facing a challenge with my Search.aspx Web Form page. It is essential for me to have the form rendered in various locations, which is why I am considering converting the Web Form into a User Control. However, the issue arises because my Sea ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

Retrieve JavaScript Variable Value when Button is Clicked via asp:HiddenField

Having limited experience with JavaScript and jQuery, I decided to make some modifications to a jQuery Slider for adjusting dates. You can check out what I've done so far here: http://jsfiddle.net/ryn_90/Tq7xK/6/. I managed to get the slider working ...

.NET development tool can't locate namespaces

My .NET MAUI project suddenly encountered an issue when I attempted to compile and debug it on an emulator. The error message states that the namespace MauiApplication in /platforms/android/MainApplication.cs cannot be located, even though no changes were ...

Steps for redirecting to the login page when the session has expired

I am facing an issue where the session is expiring but instead of redirecting to the login page, I get an error saying it cannot connect to the server. My AJAX code looks like this: function driver() { $this = $(this); $.ajax( ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

In .net, there is a substitution occurring in Request.Params where the character "+" is being replaced with a whitespace

Here is the iframe element I am working with: <iframe id="iFrameMain_01_01_01_01" frameborder="0" width="100%" height="100%" scrolling="no" style="OVERFLOW:hidden;" src="SearchGrid.aspx?SearchName=fey&amp;Code=01_01_01_01&a ...

Utilize regular expressions to substitute a specific string of text with an HTML tag

My task is to transform this text: let text = "#Jim, Start editing to see some magic happen!"; into this format: text = "<span style="color:red">#Jim</span>, Start editing to see some magic happen!"; Here is my ...

Experiencing a WEB3js error in a Vite, React, TypeScript application: Troubleshooting TypeError with callbackify function absence

Hey there, I've been experimenting with using web3 in a React client application (specifically with vite react-ts). When trying to call web3.eth.net.getId(), I encountered an error mentioning that callbackify is not a function. After some investigatio ...

Having trouble with MongoDB (Mongoose) `findByIdAndDelete` not working as expected when testing with Postman

My Mongoose code is in a separate file named model.js, while the Express code for handling http requests is in app.js. I am practicing creating APIs and testing them on Postman for an imaginary wiki article website. The specific API that is causing me trou ...

Can we use classlist for adding or removing in Angular 2?

One of the features in my project is a directive that allows drag and drop functionality for elements. While dragging an element, I am applying classes to both the dragged element and the ones it's being dragged over. This is how I currently handle it ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

Switch out the second to last symbol

Is there a way to delete the second-to-last character from a string? For instance string = '96+658-+';<br /> fixInput(string); function fixInput(string) { // string= string.replace(/[-+x÷]$/,''); // incorrect // string= ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

Mistake in Timestamp Separation - JavaScript

I have a Timestamp retrieved from MSSQL and displayed on a Webclient. The timestamp reads: Thu Jan 01 18:00:00 CET 1970, however, I am only interested in the time format: 18:00 or 18:00:00 (preferably the former). <script> var timestamp = ...