首页 > 解决方案 > Mongoose 模型中数组的 .populate() 问题

问题描述

我目前在我的模型上使用 .populate() 时遇到了一系列字典数组的问题。我将用户的购物车(字典数组)推送到用户的历史记录(数组数组)中。我希望能够显示用户过去购物车/购买历史的产品信息。

它没有通过数组矩阵内部的第二层到达字典,它可以填充实际模型而不仅仅是显示字典。问题出在我无法单独调用每个数组或好像在循环中一样的地方。这是模型和控制器功能:

// User Model
mongoose.model("User", new mongoose.Schema({
...
    cart:[ { "item":{ type:ObjectId, ref:"Product" }, "quantity": {type:Number, required:true}} ],
    history:[ [{ "item":{ type:ObjectId, ref:"Product" }, "quantity": {type:Number, required:true}}] ], // array of cart arrays
...
));

//User Controller
User.find({_id:req.params.id})
.populate({
    model:"Product",
    path:"cart.item", // this works just fine
    populate: {
        model: "Product",
        path: "history.item" // this has no effect (obviously, should be something like history.x.item to iterate through the arrays in history)
    }
})
.exec((err, userArray)=> {
    if(err) {
        res.json({errors: "Could not find user"});
    }
    else {
        let user = userArray[0];
        console.log(user.history)               
        res.json(user);
    }
});

.populate() 在 cart 属性上正常工作,并且确实从指定的 Product 模型中提取,如下所示。这就是我希望它为历史中的每个数组的每个数组所做的事情。

// user.cart.item;
(2) [{…}, {…}]
0: {
    item: { // .populate() executed correctly here
        createdAt: "2018-05-01T19:01:13.439Z"
        desc: "Marine Layer - Summer Tunic"
        inventory: 3
        name: "Bali Tunic"
        photosrc: "tunic.jpg"
        price: 88
        updatedAt: "2018-05-17T21:33:01.121Z"
        _id: "5ae8b9790a739c3a6409c6ca"
    }
    quantity:1
    _id:"5afdf50ddb9d9131bc31f79f"
}
1: { item: {…}, quantity: 2, _id: "5afdf512db9d9131bc31f7a0" }

它不适用于历史,因为模型上不存在 user.history.item - 在调用 .populate() 之前需要一个 for 循环或其他东西来遍历历史数组的索引:

// user.history.item:
(5) [Array(2), Array(2), Array(3), Array(3), Array(3)]
0:Array(2)
    0:{
        item: "5ae8b9790a739c3a6409c6ca", //not populating here
        quantity: 2,
        _id: "5af24260dce6852f10cb7937"
    }
    1:{ item: "5ae8ea78fc63980820a88478", quantity: 3, _id: "5af24266dce6852f10cb7938"}
1:(2) [{…}, {…}]
2:(3) [{…}, {…}, {…}]
3:(3) [{…}, {…}, {…}]
4:(3) [{…}, {…}, {…}]

我尝试了各种重组方式,但仍然得到相同的结果。任何见解将不胜感激!

标签: arraysmongodbmongoose

解决方案


推荐阅读