Issue when attempting to update user profile picture using Mongoose schema and Cloudinary

 updateProfile: async function(req, res) {
    try {
        const update = req.body;
        const id = req.params.id;

        if (!req.files || Object.keys(req.files).length === 0) {
            return res.status(400).send('No files were uploaded.');
        }


        const image = req.files.profileImage;

        const cloudFile = await upload(image.tempFilePath);
        const profileImage = cloudFile.url

        console.log('Loging cloudfile', profileImage)

        await User.updateOne(id, { update }, { profileImage }, { new: true },
            function(err, doc) {
                if (err) {
                    console.log(err)
                }
                if (doc) {
                    return res.status(200).send({ sucess: true, msg: 'Profile updated successful' })
                }
            });

    } catch (error) {
        res.status(500).json({ msg: error.message });
    }

}

But I am encountering an issue with the message "Callback must be a function, got [object Object]".

I attempted to use $set for both update and profileImage but the problem persists.

The image is successfully uploaded to cloudinary, however, there seems to be an issue with updating the mongoose database.

Answer №1

After a quick investigation into the issue, it appears that there may be some confusion in the arguments provided. Objects can sometimes be tricky to understand, but not to worry.

The code snippet in question is as follows:

await User.updateOne(id, { update }, { profileImage }, { new: true }

However, I believe a more accurate format would be:

await User.updateOne({id: id}, { profileImagine: profileImage, new: true },

The API documentation outlines how this function should be used:

const filter = { name: 'John Doe' };
const update = { age: 30 };

const oldDocument = await User.updateOne(filter, update);
oldDocument.n; // Number of documents matched
oldDocument.nModified; // Number of documents modified

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

Angular and MySQL in action!

I've been experimenting with Express, Angular, and MySQL. I have successfully connected to MySQL and can retrieve JSON data from the database. However, I am facing issues accessing the data in Angular. Below is my simple code: // Database Configurati ...

What is the correct way to set up a click event listener for a radio button?

Currently, I am in the process of dynamically generating HTML radio buttons. Each button is assigned an Id stored in a variable. My goal is to add a click event handler to these radio buttons using the assigned Id. However, I am encountering an issue where ...

Unable to pass data to the onChange event for the material-ui datePicker components

Need help with a form that includes a material-ui DatePicker. Here is an example: <DatePicker name="startDate" autoOk={true} floatingLabelText="startDate" onChange={(x, event) => {console.log(arguments);}} /> When I change the date, the console ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

The error message is failing to display the mat error

I've implemented the Mat control date range input control in my project and I'm facing an issue regarding displaying an error message when the user forgets to enter either the start date or end date. Below is the HTML code: <mat-form-field> ...

I am looking to have three rows of input text area comments instead of just one

Utilizing Bootstrap 4.3.1 with React Components I currently have this image: https://i.sstatic.net/rudsE.png And I am aiming for this design: https://i.sstatic.net/VmyTW.png comments: { elementLabel: "Comments", elementType: 'textar ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

Using asynchronous data in Angular 2 animations

Currently, I have developed a component that fetches a dataset of skills from my database. Each skill in the dataset contains a title and a percentage value. My objective is to set the initial width value of each div to 0% and then dynamically adjust it t ...

Can someone please help me figure out why the "setInterval" function in my script isn't functioning as expected?

I've been experimenting with controlling the refresh rate of drawn objects in a canvas using JavaScript. Even after going through the tutorials and examples on w3.school, I'm still unsure why the "setInterval" function is not executing the "gener ...

execute a retrieval query on an html pop-up

I have recently created an HTML web resource that I am displaying when a ribbon button is clicked. Within this popup, there is a dropdown list that I intend to fill with records obtained through a fetchXml query. The issue I'm encountering is that de ...

Using the find() function in Mongoose allows the use of a variable as a model

Would it be feasible to employ a variable in place of the model name when using the find() function in mongoose? For instance, if my website is capable of displaying photos and videos based on the last part of the URL, which could be either /photo or /vide ...

Custom options in MUI Autocomplete are not displaying the selected option

I am currently implementing MUI v5's Autocomplete for a dropdown feature on my website. Within this dropdown, I have options that include both a title and an id. My goal is to store the selected option's id in the state while also updating the d ...

Identifying the presence of a particular cookie

I'm currently working on a project that already has several cookies stored. My goal is to determine if the cookie labeled "login" exists. Below is the code snippet I am using: if (document.cookie.indexOf("login") >= 0) { alert("login cookie ex ...

Synchronize React Hooks OnchangeORSync React Hooks On

Currently, I am in the process of transitioning my app from using a class model to utilizing hooks. In my code, there is a dropdown list where the onChange method performs the following function: filter(event) { this.setState({ selectedFilter: ...

Automatically update the Vuex state with dynamic data

In the root component, I am looking to load a different version of state based on a specific 'data' variable. App.vue: export default { store: store, name: 'app', data() { clientId: 1 } } store.js: export const store = ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Using knockout to retrieve the attribute value with an onClick event

Snippet of HTML View with attribute value 'Qref'. This is the sample HTML Code for binding Currently, I have manually inputted the Qref Attribute value <!--ko if:$parent.Type == 2 --> <input type="checkbox" data-bind="attr:{id: $data ...

Transmitting information from the form to the server

When trying to send formdata to an endpoint, I encounter an issue with the required data fields: token_key, customer_id, folder_id, document_id, file The steps I follow are as follows: In my HTML file: submitBtn.addEventListener("click", funct ...

Creating a like and dislike button using Jquery's ajax functionality

Hey everyone, I'm currently working on implementing a like and dislike button similar to Facebook's on my website. I have a list of posts displayed using PHP loops and I want a single button to change color to blue if liked and remain the default ...