Skip to content
Advertisement

MongoDB FIND method does not work in code

so when I try to find items in a collection through the console using the method db.DB_NAME.find({ x: y }, it works just fine. However, when trying to do the same in the code, it does not work.

Perhaps it is worthy mentioning that the method findOne works great within the code.

Consulting through the console

Code:

app.get("/api/customer/:cpf", async (req, res) => {
  const properties = await Customer.consult(req);
  console.log(properties);
  res.status(200);
  res.end();
});

static async consult(req) {
    const conn = await client.connect();
    const db = conn.db("website");
    const cpf = req.params.cpf.toString();
    console.log(cpf);
    const properties = await db.collection("Property").find({
      customerCpf: cpf,
    });
    return properties;
  }

What I get from these pieces of code is a huge and weird (for me, a beginner) object in my console instead of the three expected objects.

Advertisement

Answer

Well, i see you dont use mongoose.

What you get from .find() is an cursor. You need to convert it to an array:

const properties = await db.collection("Property").find({
  customerCpf: cpf,
}).toArray();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement