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
in this line it is neccessary:
req.user
you should accessreq.body.user
But – what is the object you sent into the request named – User or UserData?
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()>
You should convert ObjectId to string.