Issue populating array of object ids

50 views Asked by At

I'm not sure why it doesn't work anymore. When i print all books in my cart i get:

{
  products: [ { quantity: 1, _id: new ObjectId('65c9bf8f9d8b1b868124bfa8') } ]
}

So it's not being populated.

This is my app.js:

app.get("/cart", async (req, res) => {
  if (req.isAuthenticated()) {
    const user = await User.findOne({ _id: req.user._id }).populate(
      "cart.products.product",
    );

    console.log(user.cart);

    res.render("cart", {
      user: user,
    });
  } else {
    res.redirect("/api/auth/login");
  }
});

this is my user schema:

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

const userSchema = new mongoose.Schema({
  username: String,
  email: String,
  password: String,
  books: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  cart: {
    products: {
      type: [
        {
          product: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Book",
          },
          quantity: {
            type: Number,
            default: 0,
          },
        },
      ],
      default: [],
    },
  },
  phone_number: {
    type: String,
    default: "",
  },
  address: {
    type: String,
    default: "",
  },
});

userSchema.virtual("cart.totalProducts").get(function () {
  let totalBooks = 0;

  this.cart.products.forEach((product) => {
    totalBooks += product.quantity;
  });

  return totalBooks;
});

userSchema.virtual("cart.totalPrice").get(function () {
  if (this.cart == undefined || this.cart.products.length == 0) {
    return 0;
  }

  let totalPrice = 0;

  this.cart.products.forEach((product) => {
    totalPrice += product.product.price * product.quantity;
  });

  return totalPrice;
});

userSchema.plugin(passportLocalMongoose, {
  selectFields: "username email",
  errorMessages: {
    MissingPasswordError: "Please enter a password",
    MissingUsernameError: "Please enter a username",
  },
});

module.exports = mongoose.model("User", userSchema);

Any ideas would be appreciated.

I tried changing the populate field but idk if it's even the right path.

dsahdsidsaoidisoahdioasdiosaiodassadnjpasjdsiahdosahdsahidhasihdoias

1

There are 1 answers

0
Yong Shun On

Suspect that the schema for the cart.products is incorrect.

Try applying the schema for cart as below:

cart: {
  products: [
    {
      quantity: {
        type: Number,
        default: 0,
      },
      product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Book",
      }
    }
  ]
}

And ensure that the reference collection (ref) is correct.