Home > Back-end >  Mongoose aggregate returns pipeline query
Mongoose aggregate returns pipeline query

Time:04-15

So I'm having a bit of trouble here with this part of my backend.

When I try to filter my document, it returns the pipeline.

Here's the code and the output.

I'm pretty sure I'm doing something wrong, but I can't see it and I've spent around 2 hours trying different aggregate methods but none of them works.

If I use the same aggregate code on the MongoDB Compass software, it returns what it is supposed to return.

Hope someone can help me and thank you for your time.

Mongoose model

const AccesoClientes = new mongoose.Schema(
  {
    cliente: { type: String, required: true },
    servidorCliente: { type: String, default: "" },
    credenciales: { type: String, default: "" },
    servidorSql: { type: String, default: "" },
    servidorServicios: { type: String, default: "" },
    programas: { type: Array, default: ["Sige"] },
    tipo: {type: String, default: ""},
    notas: { type: String, default: "" },
  },
  { timestamps: true }
);

Express call

router.get("/todos", async (req, res) => {
  const type = req.query.filter;
  let registro;
  try {
    if (!type) {
      registro = await AccesoClientes.find();
    } else {
      pipeline = [{$match: {tipo: type}}]
      registro = AccesoClientes.aggregate(pipeline, {allowDiskUse: true});
      console.log(type);
    }
    res.status(201).json(registro);
  } catch (err) {
    res.status(501).json(err);
  }
});

Output

{
    "_pipeline": [
        {
            "$match": {
                "tipo": "interno"
            }
        }
    ],
    "options": {
        "allowDiskUse": true
    }
}

Expected output

{
        "_id": "625847c2fcd6a676fc85b19f",
        "cliente": "Alpex",
        "servidorCliente": "172.27.100.14",
        "credenciales": "CLOUD",
        "servidorSql": "172.27.100.12",
        "servidorServicios": "172.27.100.17",
        "programas": [
            [
                "Pool",
                "Sige"
            ]
        ],
        "notas": "",
        "createdAt": "2022-04-14T16:11:46.899Z",
        "updatedAt": "2022-04-14T16:11:46.899Z",
        "__v": 0,
        "tipo": "interno"
    }

CodePudding user response:

You have to execute the aggregate. Right now you are just defining it but not executing it.

Try this

registro = await AccesoClientes.aggregate(pipeline, {allowDiskUse: true});

This is similar to how you are doing await AccesoClientes.find()

  • Related