I am experiencing issues with my local MongoDB database not properly storing data when using Express and Mongoose

I am encountering an issue where my code is functioning correctly in the console but it is not saving data to the database. Every time I restart the server, the data gets reset. While I can read data from the database without any problem, the issue arises when trying to update or create new data as intended. Below is the snippet of code from my server.js file:

    var express = require('express');
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var bodyParser = require('body-parser');
    var app = express();

    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost:27017/food');


    //Allow all requests from all domains & localhost
    app.all('/*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
      res.header("Access-Control-Allow-Methods", "POST, GET");
      next();
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));


    var usersSchema = new Schema({
      _id: String,
      id: String,
      vote: Number
    });

    var bkyes = mongoose.model('bkyes', usersSchema);


    app.post('/bkyes', function(req, res, next) {

    bkyes.find({}, function(err, foundObject) {
      console.log(foundObject);  //Print pre-update
      var found = foundObject[0];
      found.vote = req.body.vote; //Passing in the number 5 here(was -1 before)
      found.save(function(err) {

          console.log(foundObject); //Print post-update
        });
      });
    });


    app.listen(3000);

    /*
    The console.log pre-update:
    [ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: -1 } ]
                                                                   ^
    The console.log post-update:
    [ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: 5 } ]
                                                                  ^
    However this data does NOT write to the db and just resets when you restart the server!!
    */

Answer №1

The foundObjects does not get affected by the save() function at all, making the logs somewhat pointless.

I am unclear why you are trying to retrieve every document from bkyes and extract the first one. Typically, you would search for a document based on certain conditions, often using the _id field.

However, here is an example utilizing findOneAndUpdate():

bkyes
  .findOneAndUpdate({
    // Conditions
    _id: '00001'
  }, {
    // Specify which fields to update
    vote: 5 
  })
  .exec(function(err, foundObject) {
    if (err) {
      // Handle errors here
    }

    // Perform actions after successful update
  });

NOTES: foundObject represents the object prior to the update.

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

Convert an array into individual objects and include key-value pairs from a separate object

I am working with two arrays that have the same length: One is a simple array numbers = [4,5,6] The other is an array of objects objects = [ {type: "x", value: 7}, {type: "y", value: 8}, {type: "z", value: 9} ] My goal is to combine th ...

Searching for parameters wrongly triggering the id on a different route

Having recently delved into mongoose, I must apologize in advance for any misuse of terminology on my part. Below is the content of my routes file: const express = require('express'); const router = express.Router(); const passport = require(&a ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

The Javascript countdown feature may experience issues on Safari and IE browsers

Why does this function work in Chrome, but not on IE or Safari? function countdown(){ var dDay = new Date().getUTCDate() + 1; var dMonth = new Date().getUTCMonth() + 1; var dYear = new Date().getUTCFullYear(); var BigDay = new Date(dYear+ ...

Prepare an email message for sending

Currently, I'm working on an app using officejs. My goal is to extract content from an Excel worksheet and insert it into an Outlook email. However, I don't want the email to be automatically sent by the system. Instead, I would like the new emai ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Creating the code for Mocha to produce a fail response

I have been attempting to deliberately make the script fail by accessing/redirecting to 2 links before triggering the error case. Despite my efforts, Mocha still shows "1 passing" and only returns an error when it reaches the assertion. How can I ensure ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

I'm looking for a streamlined method to simultaneously access multiple APIs with GraphQL and React

For my client side project, I'm using GraphQL and React but opting not to use Redux for state management. Instead, I have organized my API calls into custom hook files as shown below: const [getSomeData, { data: getSomeDataData, loading: getSomeData ...

Setting the focus on an input when updating a property in the Pinia store using Vue

When a component I have is clicked, it triggers a function in the store: <button @click="this.store.foo()"></button> Within the store, I am updating a specific property: state: () => ({ focusIn: false, }), actions: { foo() { ...

Electron Web Workers do not have compatibility with NodeJS modules

I'm currently working on a desktop application using Electron paired with ReactJS. From the initial renderer process, I create a hidden BrowserWindow to launch another renderer process. Within this new renderer process, I set up a web worker that wil ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test. caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true) driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps) drive ...

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Using conditional statements like 'if' and 'else' in JavaScript can

Can someone help me with solving my problem using if-else statements in Javascript? I need to filter names by gender and save them as keys - woman / man in local storage. Any assistance would be greatly appreciated. I am struggling to figure out how to im ...

Exploring how to integrate a jQuery ajax request within Javascript's XmlHttpRequest technique

My current setup involves an ajax call structured like this: var data = {"name":"John Doe"} $.ajax({ dataType : "jsonp", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // re ...

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

Using regular expressions, you can conveniently extract text that is contained within paragraph tags

I attempted to use RegExp in JavaScript to extract text between paragraph tags, but unfortunately it isn't working... Here is my pattern: <p>(.*?)</p> The text I am trying to extract from is: <p> My content. </p> <img sr ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Is it considered acceptable to house a myriad of variables within the token object in NodeJS?

Currently working on implementing authentication with NodeJS, expressJS, mongodb and React Native. Is it acceptable to include multiple variables in the token object like shown in this example? const token = jwt.sign( { userId: user. ...