skip to Main Content

new to node.js
I’m working on a nodejs-experss-mongodb project and I’m currently implementing a subscription function with the following specific requirements:

Method: post

Url:localhost:8080/api/v1/users/:userid/subscribe/:businessid

AC:
Current user’s following array, add business id.

Add the current user id to the merchant’s follower array

The final return is 201, {user}

But every time I try to test it in postman, I get this error:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/v1/users/647965651bbc93663ec695d5/subscribe/647965651bbc93663ec695d6%0A</pre>
</body>
</html>

I’m not sure where it went wrong.
My usermodels:

import { Request, Response } from 'express';
import UserModel from '../models/User';
import mongoose from 'mongoose';

export const subscribe = async (req: Request, res: Response) => {
  const { userid, businessid } = req.params;
  
  // search for student id
  const user = await UserModel.findById(userid).exec();
  // search for business id
  const business = await UserModel.findById(businessid).exec();

  if(!user || !business){
    res.status(404).json({ error: 'user or business not found' });
    return;
  }

  if (!user.is_business) {
    return res.status(403).json({ message: 'User is not a business' });
  }

  business.follower.addToSet(userid);
  await business.save();

  user.following.addToSet(businessid);
  await user.save();
  
  return res.status(201).json({ user });
};

usermodels:

import { Schema, model } from 'mongoose';
const schema: Schema = new Schema({

  is_business: {
    type: Boolean,
    required: true,
    default: false,
  },

  following:  [{
    type: Schema.Types.ObjectId,
    ref: "User",
  },],

  follower: [{
    type: Schema.Types.ObjectId,
    ref: "User",
  }],
},

{
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at',
  }
});
export default model('User', schema);

my user routes:

import { Router } from 'express';
import { index, deactivate, activate, subscribe } from '../../controllers/users';

const userRouter = Router();

userRouter.post('/users/subscribe/:userid/:businessid', subscribe);

export default userRouter;

Anyone knows how to fix it? Any helps are appreciated!

2

Answers


  1. Your route is defined as:

    '/users/subscribe/:userid/:businessid'
    

    But, your URL is sent as:

    '/users/:userid/subscribe/:businessid'
    

    These do not match. Change one of them to match the other.

    Login or Signup to reply.
  2. Please check the URL which are you redirecting to I think
    you have written these

    • /api/v1/users/647965651bbc93663ec695d5/subscribe/647965651bbc93663ec695d6%0A

    • please redirect into these
      /api/v1/users/(subscribe_id)/647965651bbc93663ec695d5/:bussinessid

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search