0

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.

Alim Gölcük
  • 27
  • 1
  • 7

1 Answers1

0

if you want to populate the schema, you have to execute a preQuery on that schema when you execute "find" query.

First of all I think you have to update your UserSchema. Update this for your userCart in the userSchema definition: (try to avoid nesting.)

userCart: {
     type: mongoose.Schema.Types.ObjectId,
     ref: 'Product',
    },

Then, Add this Middleware query to your userSchema:

//QUERY MIDDLEWARE
UserSchema.pre(/^find/, (next) => {
    this.populate({
        path:"userCart",
    });

    next();
});

This code will be executed and would populate your data for that productId on every "find" query for your userSchema.

Let me know if you have any issues or questions.