Mongoose Model

时间:2018-05-11 19:40:45

标签: arrays mongodb mongoose

我目前在我的模型上遇到了一些字典数组的问题.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) [{…}, {…}, {…}]

我尝试过各种方式的重组,但仍然得到相同的结果。任何见解都会非常感激!

0 个答案:

没有答案