JavaScript web developer encounters an issue with MongoDb and Mongoose findOneAndUpdate method, as it unexpectedly returns undefined

I've been attempting to update an item in my mongodb database, but I'm encountering issues as the error keyword is being set to undefined. It's possible that I am making a mistake somewhere. Here's the code for the update function:

router.post("/file/:id/edit", (req, res) => {
  var id = req.params.id;
  File.findOneAndUpdate( {"_id": id} , req.body, (err) => {
  if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
  });
});

This is how the update is triggered:

export function updateFile(file) {
  var objIdToUpdate = file["id"];
  var myUpdate = axios.post("http://localhost:3001/api/file/:" + objIdToUpdate + "/edit", {
        title: file.title,
        author: file.author,
        dateCreated: file.dateC,
        dateModified: file.dateModified,
        size: file.size,
        type: file.type,
        tags: file.tags
  });
  return myUpdate;
}

Here's my schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const FileSchema = new Schema(
  {
    title: String,
    author: String,
    dateCreated: String,
    dateModified: String,
    size: String,
    type: String,
    tags: []
  },
  { timestamps: true }
);

module.exports = mongoose.model("File", FileSchema, "files");

Despite trying to print the "err" keyword, it remains undefined. What could be causing this issue with updating values in my database?

Answer №1

When working with the callback function of findOneAndUpdate, it's important to note that the err variable always contains a value. For better error handling, consider utilizing promises with then and catch like so:

File.findOneAndUpdate({ "_id":  req.params.id}, { req.body },{returnNewDocument: true})
    .then((resp) => { res.send(resp) })
    .catch((err) => { res.send(err) });

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

Is it possible to make any object reactive within Vuex?

Seeking ways to enhance the sorting of normalized objects based on a relationship. Imagine having an application that requires organizing data in a Vuex store containing multiple normalized objects, like this: state: { worms: { 3: { id: 3, na ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Utilizing session variables within a Jade template in a Node.js environment

Is there a way to avoid using session variables in jade template files without relying on dynamic helper functions and passing them through res.render()? I tried using the dynamic helpers method, but it's giving me an error because it is deprecated. C ...

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...

Instructions on transferring an xlsx file from frontend using react to backend with express, and subsequently forwarding it via email

Recently, I was working on a feature that required me to convert data from an array of arrays of objects into a spreadsheet. I successfully achieved this using the xlsx library. The next task was to send this spreadsheet as an email attachment. Everything ...

What is the best way to save the generated image in Aviary?

Here is the code snippet I'm working with: var featherEditor = new Aviary.Feather({ apiKey: 'your-client-id-here', theme: 'light', tools: 'all', appendTo: '', onSave: function(imageID, newURL) { var img = do ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

Leveraging jQuery in Content Scripts for Chrome Extensions

I am currently working on developing a Chrome extension that will prompt a small input whenever a user highlights text on a webpage (similar to Medium's feature that allows you to tweet highlighted text). While I am making progress, I believe using j ...

I am a beginner in node.js and currently exploring the concept of asynchronous callbacks and how they function

When running the following code, "one" and "two" are displayed as output but "three" is absent. Can someone provide an explanation as to why "three" is not showing up in the output? Despite trying various methods, I am still unable to pinpoint the cause ...

Guide on applying a filter to the items in a listbox using the input from a text box

In my HTML form, I have the following elements: 1) A list box containing filenames: s1.txt2013 s2.txt2013 s3.txt2012 s4.txt2012 2) A text box where the user enters a pattern (e.g. 2013) 3) A button By default, the list box contains the 4 file ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

When a JavaScript program encounters an error, the Try Catch statement will log the errors in the

This particular code snippet is designed to loop indefinitely until the user enters the correct answer in a prompt. The acceptable answers are "left" and "right". If the user inputs any other text, the function promptDirection will throw an error and execu ...

Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code: new Vue({ el: 'body', data:{ role: '', company: '', list:[], ...

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

Rearrange the order of the next button to appear after the dropdown instead of the

When a button is clicked, the paragraph area should display while pushing down the next button/div and the rest of the page below it. In simpler terms, clicking on the button reveals the box without overlapping other elements. I apologize for any language ...

Is it advisable to encrypt the database entries for Google and Facebook IDs?

When authenticating users via Google and Facebook login in my web app (MERN stack) using passport.js, I first retrieve the user's ID, encrypt it with bcryptjs, and then store it in the database. The issue arises when a user signs in, as I must retriev ...

Attempting to showcase JSON response within an HTML page using JavaScript

Can anyone help me troubleshoot my code for displaying JSON data on a web page? Here's what I have so far: <button type="submit" onclick="javascript:send()">call</button> <div id="div"></div> <script type="text/javascript ...

Why isn't the VueJS component loading state getting updated after Canceling an Axios network request?

Within my dashboard, there is a dropdown for filtering dates. Each time a user changes the dropdown value, multiple network requests are sent using Axios. To prevent additional API calls when the user rapidly changes the date filters, I utilize AbortContr ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...