MongooseError [CastError]: Cast to string failed for value "{}" at path "userData.email" for model "order"

Viewed 496

I want to get orders of given user search by email: "admin" and I am getting an error:

MongooseError [CastError]: Cast to string failed for value "{}" at path "userData.email" for model "order".

And I am not getting any response.

backend - js file:

router.get('/user-orders', (req, res) => {
  const user = req;
  Order.find({ "userData.email": user }, (error, order) => {
    if (error) {
      console.log(error);
    } else {
      return res.json({ order });
    }
  })
})

frontend - service:

 userOrders(user) {
    return this.http.get<User>(this.userOrdersUrl, user);
  }

frontend - ts file:

  constructor(private orderService: OrderService, private router: Router) {
    this.orderService.userOrders('admin').subscribe(
      res => console.log(res),
      err => console.log(err)
    );
  }

If I declare "user" in the backend - everything works well:

router.get('/user-orders', (req, res) => {
  const user = 'admin';
  Order.find({ "userData.email": user }, (error, order) => {
    if (error) {
      console.log(error);
    } else {
      return res.json({ order });
    }
  })
})

enter image description here

But I have to send the string 'admin' from the frontend. How to fix it?

Edit:

order model:

const orderSchema = new Schema({
    userData: {
        firstname: String,
        lastname: String,
        address: String,
        postcode: Object,
        city: String,
        country: String,
        email: String,
        phone: Number
    },
    items: {},
    shipping: String,
    sum: Number,
    created: {
        type: Date,
        default: Date.now()
    },
    status: {
        type:String,
        default: 'order_placed'
    }
});
1 Answers

I would change your router to expect the user-id/email in the url as a path-parameter, which express will then populate under req.params

router.get('/user-orders/:id', (req, res) => {
   Order.find({ "userData.email": req.params.id}, (error, order) => { ... });
}

Then, in your frontend you need to adjust the url to something like:

userOrders(userIdOrEmail) {
   return this.http.get<User>(`${this.userOrdersUrl}/${userIdOrEmail}`);
}
Related