Mongoose populate in array

Viewed 7164

I try to play with populate but without success ... It's possible to do this?

I have 2 shema : - User

import mongoose, { Schema } from 'mongoose'

const userSchema = new Schema({
  email: { type: String, unique: true },
  password: String,
  passwordResetToken: String,
  passwordResetExpires: Date,

  products: [{
    productId: { type: Schema.Types.ObjectId, ref: 'Product' },
    dateAdd: { type: Date, default: Date.now }
  }]
}, { timestamps: true })

const User = mongoose.model('User', userSchema)

export default User

And Product :

import mongoose, { Schema } from 'mongoose'

const productSchema = new Schema({
  domain: String,
  originUrl: { type: String },
  price: Number,
  img: String,
  userFollow: [{ type: Schema.Types.ObjectId, ref: 'User' }]
})

const Product = mongoose.model('Product', productSchema)

export default Product

So I want to retrieve all the info for each of my prodcutId

I try this way (and many others without success):

User.findOne({ _id: userId }).populate({
      path: 'products.productId',
      populate: { path: 'products.productId', model: 'Products' }
}).exec(function (err, products) {
  if (err) {
    console.log('errors :' + err)
  }
  console.log('Product => ' + util.inspect(products))
})

Populate has no effect, same result with just the findOne()

2 Answers
Related