2017-07-18 155 views
1

我试图玩填充,但没有成功... 这是可能做到这一点?猫鼬填充阵列

我有2玛: - 用户

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

+0

你没有找回'产品',而是一个'用户'与'产品'阵列。并尝试删除'模型:'产品''或'模型':'产品'。 – Mikey

回答

1

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

1

尝试使用的MongoDB aggregate功能和$ 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 
}); 
+0

我认为它应该是'localField:“products.productId”'。 – Mikey