First of all, I found a lot of answers about that problem in StackOverflow However, none of them worked on my problem.
I have an userSchema like that:
const UserSchema = new Schema({
userName: {
type: String,
required: true,
},
userSurname: {
type: String,
required: true,
},
userEmail: {
type: String,
unique: true,
required: true,
},
userPassword: {
type: String,
required: true,
},
userRole: {
type: String,
enum: ['müşteri', 'admin'],
default: 'müşteri',
},
userCart: [
{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
},
quantity: Number,
price:Number,
},
],
});
I wanted to populate the productId in array of userCart so I can reach:
const ProductSchema = new Schema({
productName: {
type: String,
unique: true,
required: true,
},
productBrand: {
type: String,
required: true,
},
productPrice: {
type: String,
required: true,
},
productPhoto: {
type: String,
required: true,
},
productQuantity: {
type: Number,
required: true,
},
slug: {
type: String,
unique: true,
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category',
},
});
those fields.
I tried
const products = await User.findById(req.session.userID).populate('userCart');
and
const products = await User.findById(req.session.userID).populate('userCart.productId');
and I thought it might be because of findById so instead of findById I tried findOne and that one also didn't work.
And after doing that I tried to reach in ejs file like that but it shows nothing.
<% for(let i =0; i< products.userCart.length; i++) { %>
<div>
<%= products.userCart[i].productName %>
</div>
<% } %>
Any help is appreciated, thanks in advance.