arrays - 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) [{…}, {…}, {…}]
我尝试了各种重组方式,但仍然得到相同的结果。任何见解将不胜感激!
解决方案
推荐阅读
- vba - 尽管检查为 FALSE 且 [value_if_false] 为 0 或 1,但 IF 语句错误
- sql-server - SQL Server 的虚拟服务器和物理存储
- python - 如何使用 OR 条件合并两个 pandas 数据框
- javascript - 正则表达式删除数字和其他字符
- neural-network - 人工神经网络感知中零输入偏差的含义
- python - TKinter & Python:如何给进程名称?
- python-3.x - Tensor("pow:0", ...) 必须与 Tensor("Cast_2:0", ...) 来自同一个图
- java - Declaring dependency on Mockito using Maven/pom.xml in IntelliJ IDEA
- javascript - firebase 函数 + 实时数据库 - 数据库结构和代码
- node.js - 如何使用 oracledb node js 打印带有绑定变量的 sql 或 pl/sql