4

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()

1
  • You are not getting back products but one user with an array of products. And try removing model: 'Products' or doing model: 'Product'. Commented Jul 18, 2017 at 14:03

2 Answers 2

8

I think User.findOne({ _id: userId }).populate('products.productId') should work.

Sign up to request clarification or add additional context in comments.

Comments

1

Try using aggregate function of MongoDB and $lookup.

Users.aggregate([ { "$match": { _id: user.id } }, { "$lookup": { from: "Product", localField: "products", foreignField: "_id", as: "products" } } ]) .exec() .then((result) => { //your result }) .catch((err) => { // if any error }); 

1 Comment

I think it should be localField: "products.productId".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.