mongoose在数组中填充

我尝试玩填充,但没有成功…有可能做到这一点?

我有2个shema: – 用户

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 

和产品:

 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 

所以我想检索我的每个prodcutId的所有信息

我尝试这种方式(和其他许多没有成功):

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

填充没有效果,只有findOne()的结果相同

我认为User.findOne({ _id: userId }).populate('products.productId')应该工作。

尝试使用MongoDB的聚合函数和$ 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 });