Home > database >  How can I pass an object property to a route?
How can I pass an object property to a route?

Time:08-24

I have a local server that I have created to learn and practice my backend coding. I wrote an order schema like this:

const schema = new mongoose.Schema({
  products: [
    {
      _id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product',
      },
      name: { type: String },
      price: { type: Number },
      obs: { type: String, required: false },
    },
  ],
  owner: {
    _id: {
      type: mongoose.Schema.Types.ObjectId,
      unique: false,
    },
    table: {
      type: Number,
      required: false,
    },
  },
  status: {
    type: Number,
...
});

And I have controllers like this that works already:

ordersController.get('/status/:status', async (req, res, next) => {
    const findByStatus = await orderService.findByStatus(req.params.status);
    return res.json(findByStatus);
});

But I'm trying to get the orders by owner.table, and I don't know how to pass the exact parameter to the route:

ordersController.get('/owner/table/:owner.table', async (req, res, next) => {
});

All help is greatly appreciated!

CodePudding user response:

I think you are mixing up concepts.

Params in the URL (e.g. :status) are just arbitrary strings.

This would still work

ordersController.get('/status/:abcd', async (req, res, next) => {
    const findByStatus = await orderService.findByStatus(req.params.abcd);
    return res.json(findByStatus);
});

You have to write a function that will get this data for you, for example findByOwnerAndTable

ordersController.get('/owner/:owner/table/:table', async (req, res, next) => {
    const findByStatus = await orderService.findByOwnerAndTable(req.params.owner, req.params.table);
    return res.json(findByStatus);
});

CodePudding user response:

What I believe you're looking for is res.locals. res.locals is an empty object living on your res parameter passed between middleware and controllers that is conventionally used to store information needed by other middleware in the chain.

TLDR: Put information you want to access between middleware on res.locals.

  • Related