Search code examples
node.jsmongoose

I am receiving a 500 internal server error for my GET request in Node.JS


I'm trying to display the user's saved recipes by attaching a usersID with the recipeID. when I make the GET request. I'm getting back an empty object with no properties. What exactly is going on with this code?

Here are the savedRecipe routes:

router.get('/savedRecipes/ids/:userID', async (req, res) => {

    const {userID} = req.params
    try {
        const user = await UserModel.findById(mongoose.Types.ObjectId(userID));
        res.status(201).json({ savedRecipes: user?.savedRecipes });
      } catch (err) {
        console.log(err);
        res.status(500).json(err);
      }
})


router.get('/savedRecipes/:userID', async (req, res) => {

    const {userID} = req.params

    try {
        const user = await UserModel.findById(mongoose.Types.ObjectId(userID));
        
        const savedRecipes = await RecipeModel.find({
          _id: { $in: user.savedRecipes },
        });
    
        console.log(savedRecipes);
        res.status(201).json({ savedRecipes });
      } catch (err) {
        console.log(err);
        res.status(500).json(err);
      }
})

Solution

  • You don't need to write UserModel.findById(mongoose.Types.ObjectId(userID)), just write UserModel.findById(userID)

    I assume that "savedRecipes" is an Array of "Recipe _ids" like ["64aaea3d0ce4282f14604767", "64aaea3d0ce4282f1460476s"] this,

    So the problem is here,

    const savedRecipes = await RecipeModel.find({
          _id: { $in: user.savedRecipes },
    });
    

    Here _id is Mongoose ObjectId and user.savedRecipes is an Array of Strings

    You can't compare Strings with Mongoose ObjectID. So save the recipe _ids as Mongoose ObjectID in the "savedRecipes" Array.

    To save the id as Mongoose ObjectId, change the Schema like this,

    const UserSchema = new mongoose.Schema({
         //...
         savedRecipes: [mongoose.Types.ObjectId]
    })
    

    Or use new mongoose.Types.ObjectId(recipeID) when saving it to the savedRecipe array.