skip to Main Content

Address Function :-

export const GetAddress = async (req, res) => {
  let user = req.user;
  try {
    if (!user) {
      res.status(404).json({ message: "User not Found", success: false });
      return;
    }

    let id = await user.address[0];
    console.log(id);
    let addresses = await Address.findById(id);
    console.log(user);
    if (!addresses) {
      res.status(404).json({
        message: "No Address Found",
        success: false,
      });
      return;
    }

    res.status(200).json({
      message: `Welcome Back`,
      addresses,
      success: true,
    });
  } catch (error) {
    console.log(error);
    ErrorHandler(res, error);
  }
};

UserData :-

{
  _id: new ObjectId('657be59e80baafa1288a5169'),
  firstName: '***',
  lastName: '**',
  email: '*******@gmail.com',
  password: '$2a$10$cfJUXElsffQaM6T0QCA03O5XomIyVhLgALE3auxQzkpgCysJLY0Ei',
  address: [
    new ObjectId('657da734d4f75aa0f22a051e'),
    new ObjectId('657da86fd4f75aa0f22a053a'),
    new ObjectId('657da8e0d4f75aa0f22a054e'),
    new ObjectId('657da9fbd4f75aa0f22a0552'),
    new ObjectId('657daa22d4f75aa0f22a0556')
  ],
  cart: [],
  __v: 0
}

Now as you can see I already have addresses in user’s profile even after that if I try fetch a address using the address function it still throws the error

2

Answers


    1. Is mongoose installed and imported?
    2. In this line you’re drawing data from req object (not from mongoose) so using ‘await’ isn’t neccessary:
    let id = user.address[0];
    

    in this line it is neccessary:

    let addresses = await Address.findById(id);
    
    1. Most likely that instead of req.user you should access req.body.user

    But – what is the object you sent into the request named – User or UserData?

    1. Have you tried to refer to object id as mongoose.Types.ObjectId?

    about mongoose objectId:
    Output for ObjectId is a complex type (that contains value-kay pairs).

    When inserting to db – the expected type should be <mongoose.Schema.Types.ObjectId> and then no conversion is needed.
    Trying to read or compare ObjectId – adding .toHexString() is needed (because its a complex type) <User.address[0].toHexString()>

    1. When printing it, it should be one of these two options:
    console.log(id.toHexString());
    
    console.log(req.body.user.address[0].toHexString());
    
    Login or Signup to reply.
  1. You should convert ObjectId to string.

    let id = await user.address[0]; // The type of id is ObjectId.
    console.log(id);
    let addresses = await Address.findById(id.toString()); // Convert ObjectId to string
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search