'Mongoose populate() returns null, not answer found

I'm trying to populate the 'category' field to show the names in a select, but after executing the populate() method, the field has 'null' values.

It's a budgeting web app. First project, sorry if its a little messy.

At first sight could seem as a duplicated question, but none of the answers apply to my code... (I already checked and rechecked ;) ).

The data is saved correctly to db, checked in atlas and/or Robo3T.

The db models:

    const presupuestoSchema = new mongoose.Schema({
    
      budgetName: String,
      accounts: [{
        accountName: String,
        accountType: Schema.Types.ObjectId,
        accountAvailable: {
          type: Number,
          default: 0
        }
      }],
      categories: [{
        categoryName: String,
        categoryAvailable: {
          type: Number,
          default: 0
        },
        categoryAssigned: {
          type: Number,
          default: 0
        }
      }]
    });
    
    const Presupuesto = mongoose.model("Presupuesto", presupuestoSchema);
    
    const transactionSchema = new mongoose.Schema({
      date: Date,
      account: {
        type: Schema.Types.ObjectId,
        ref: "Presupuesto"
      },
      payee: String,
      category: {
        type: Schema.Types.ObjectId,
        ref: "Presupuesto"
      },
      description: String,
      amount: Number
    });
    
    const Transaction = mongoose.model("Transaction", transactionSchema);

And the code:

    app.get("/accounts", function(req, res) {
    
      Presupuesto.find({}, async function(err, foundBudget) {
        if (err) {
          console.log(err);
        } else {
          if (foundBudget.length > 0) {
            const cashAccountId = foundBudget[0].accounts[0]._id;
            const debitAccountId = foundBudget[0].accounts[1]._id;
            let cash = foundBudget[0].accounts[0].accountAvailable;
            let debit = foundBudget[0].accounts[1].accountAvailable;
            const budgetId = foundBudget[0]._id;
            const categories = foundBudget[0].categories;
    
            let transactions = [];         //////////////// here populate()
            Transaction
              .find({})
              .populate("category")
              .exec(function(err, foundTransactions) {
                if (err) {
                  console.log(err);
                } else {
                  transactions = foundTransactions;
                  console.log("Found transactions: -get-");
                  console.log(foundTransactions);
    
                  res.render("accounts", {
                    cashAvailable: cash,
                    debitAvailable: debit,
                    budgetId: budgetId,
                    cashAccountId: cashAccountId,
                    debitAccountId: debitAccountId,
                    transactions: transactions,
                    moment: moment,
                    categories: categories
                  });
                }
              })
    
          } else { // not found budget
            console.log("Not transactions found." +
              " Creating example budget.");
    
            try {
              await presupuestoTest.save();
              res.redirect("/accounts");
            } catch (e) {
              console.log(e);
              res.status(400).send(e);
            }
    
          }
        }
      })
    
    });

Output:

    Listening on port 3000...
    Not transactions found. Creating example budget.
    Found transactions: -get-
    []
    Transaction successfully saved to db.
    {
      acknowledged: true,
      modifiedCount: 1,  
      upsertedId: null,  
      upsertedCount: 0,  
      matchedCount: 1    
    }
    New account total updated successfully
    Found transactions: -get-
    [
      {
        _id: new ObjectId("61ed7cd2f699c24da45c1da5"),
        date: 2022-01-19T00:00:00.000Z,
        account: new ObjectId("61ed7bcef699c24da45c1d79"),
        payee: '',
        category: null,
        description: '',
        amount: 5445,
        __v: 0
      }
    ]

Thanks in advance for your help.

I already tried deleting dbs



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source