Every time findByIdAndUpdate runs, it seems to get tangled up in the

Whenever I try to run findByIdAndUpdate, it doesn't seem to work as expected and ends up in the catch block. I am sending responses to Postman using res.json(req.user.id) and res.json(profileFields). The response I receive when I use profileFields

{
    "user": "5b3134a0e2543b06d130a5d7",
    "handle": "wadeaston1",
    "status": "Developer",
    "skills": [
        "HTML",
        " CSS",
        " Javascipt"
    ],
    "social": {}
}

I'm confused because all my fields are passing values as expected into user and $set. I can't figure out why it's going to the catch block.

 Profile.findByIdAndUpdate(
      { user: req.user.id },
      { $set: profileFields },
      { new: true }
    )
      .then(profile => res.json(profile))
      .catch(err => {
        res.json("Timeout");
        console.log("HI");
      });

This is my Profile Schema:

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

//Create Scheme
const ProfileSchema = new Schema({
  user: {
    //this will associate user by their ID
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  handle: {
    type: String,
    required: true,
    max: 40
  },
  company: {
    type: String
  },
  website: {
    type: String
  },
  location: {
    type: String
  },
  status: {
    type: String,
    required: true
  },
  skills: {
    //Array of strings
    type: [String],
    required: true
  },
  bio: {
    type: String
  },
  githubusername: {
    type: String
  },
  experience: [
    {
      title: {
        type: String,
        required: true
      },
      company: {
        type: String,
        required: true
      },
      location: {
        type: String
      },
      from: {
        type: Date,
        required: true
      },
      to: {
        type: Date,
        required: true
      },
      current: {
        type: Boolean,
        default: false
      },
      description: {
        type: String
      }
    }
  ],
  education: [
    {
      school: {
        type: String,
        required: true
      },
      degree: {
        type: String,
        required: true
      },
      fieldofstudy: {
        type: String,
        required: true
      },
      from: {
        type: Date,
        required: true
      },
      to: {
        type: Date,
        required: true
      },
      current: {
        type: Boolean,
        default: false
      },
      description: {
        type: String
      }
    }
  ],
  social: {
    youtube: {
      type: String
    },
    twitter: {
      type: String
    },
    facebook: {
      type: String
    },
    linkedin: {
      type: String
    },
    instagram: {
      type: String
    }
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);

Answer №1

findByIdAndUpdate is used to locate a document for updating based on its _id, however in this case you are looking for the document based on the user field. Therefore, it would be more appropriate to use findOneAndUpdate:

Profile.findOneAndUpdate(
      { user: req.user.id },
      { $set: profileFields },
      { new: true }
    )
    .then(...

It is unnecessary to manually convert req.user.id to an ObjectId as Mongoose will handle this conversion for you according to how the user field is defined in your schema.

Answer №2

If you encountered an error, it appears that you may need to convert req.user.id from a string to an ObjectId:

Profile.findByIdAndUpdate(
  { user: new mongoose.Types.ObjectId(req.user.id) },
  { $set: profileFields },
  { new: true }
).then( /* rest of code */

This assumes you have included

const mongoose = require('mongoose')
or something similar in your code.

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 Ajax request was a success, but I am unable to retrieve radio button values from the $_POST variable

My website operates fully asynchronously, generating and destroying HTML elements on button clicks that prevent navigation. In this section, I am creating a form with an array of radio boxes for rating from 1 to 10. This form is submitted using jQuery.aja ...

Delay the execution of a function until subscription within RxJS and React's setState

One of the interesting features of RxJS is the function called fromCallback. This function takes a callback as its last parameter and returns an Observable. I am intrigued by the idea of combining this with React's setState function to achieve somethi ...

Which is Better: Parsing Django Models on the Server Side or Client Side?

What is considered the most effective practice for displaying model objects on the client side while working on Django app development? Is it recommended to parse the models using server-side code or is it better to utilize client-side templating languages ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

Using React Native to trigger a function based on a conditional statement

<Pressable onPress={()=> { if(newID) { EditPress(newID) } else { AddPress } }} style={styles.logBox} > <Text style={{ textAlign:"center", ...

Creating a clear, white overlay that separates an image from the content on a webpage

I am currently working on creating a background for OP.gif. The goal is to have a transparent white color covering the entire web page, and to have the input[type='text'] below that coverage also in transparent white color. This way, the end-user ...

Passing PHP value from a current page to a popup page externally: A guide

I'm currently facing an issue at work where there is a repetitive button and value based on the database. I need to extract the selected value from the current page into a pop-up page whenever the corresponding button is clicked throughout the repetit ...

"Switching Classes with a Click Event: A Step-by-

This script is designed to work with SoundCloud's widget in order to enable remote text buttons. I am attempting to modify it so that it functions as a remote for an image button that toggles between different pictures for pause and play, rather than ...

Maintaining a continuous MongoDB connection (version 2.0) within a Node.js Express application

Currently facing a bit of difficulty with what should be an easy task. I am in the process of setting up an express (4) application with the native mongodb (2) driver and exploring how to establish a connection to the mongo server/db once, maintain it thro ...

Utilizing ngModel bindings in AngularJS to link controller data, or invoking functions through ngModel

I am attempting to link an unspecified array index based on a certain property in angularjs. <select id="iditemtype" ng-model="bindSpecificAttribute(entity, e)" ng-options="e as e.configValue for e in allConfig() | filter:{typeName:'It ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

PHP code successfully writes to a file on a local machine, but encounters issues when attempting to write to

I set up a basic website that was functioning perfectly on my localhost. However, once I transferred it to an IIS Windows 2008r2 server, my PHP scripts stopped writing to my JSON files. Despite confirming that the server has PHP installed, I am at a loss a ...

Adding new data to MongoDB alongside a corresponding key-value pair

I need to locate a specific object within an array, then insert additional data next to the matching key/value pair. Here is a sample scenario: profile = [ { data: 'value', array: [ 'one', 'three&a ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

Exploring the depths of nested lists in MongoDB: A guide to using aggregate queries within lists

In my database, I have a group of documents called "EvaluationGroups", each containing a list of Evaluations. Each Evaluation object further contains a list of Detail objects, and each Detail includes a list of Label objects. A Label object consists of two ...

Exploring the best way to use $set in Mongoose for dynamically updating an embedded

I'm currently attempting to create a unique function that can update the value of a specific embedded MongoDB document within an array. The goal is to change the value based on its position. function removeAddress(accountNum, pos) { const remove ...

Utilizing Angular Directives and Controllers for Improved Efficiency

I have developed a custom dropdown option selector which is functioning well. It includes functions to fetch data from a specified URL in order to populate a list. However, the issue arises when I attempt to reuse this component in a different section of ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

Attempting to alter CSS styles programmatically using JavaScript is proving to be ineffective

After trying numerous methods, I have come to the conclusion that the current approach works for others but not for me. Can anyone suggest an alternative way to write this code? Current CSS .aw-widget-current-inner div.aw-widget-content a.aw-current-weat ...

Three.js canvas: Switching to a new texture for the upcoming panorama image

What is the recommended approach for displaying the next panorama with image changes? Steps to achieve this: var textures = [ loadTexture( 'PANO_NEXT0001.jpg' ), // right loadTexture( 'PANO_NEXT0003.jpg&apo ...