node.js - Mongoose:使用对象数组查找所有模型
问题描述
我有这个模型:
const cart = new mongoose.Schema(
{
products: [{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
quantity: {
type: Number,
required: true,
default: 1
},
title: String,
price: Number
}],
},
{ timestamps: true });
我如何使用它找到我的所有产品(来自 Model Product)。
cart = Cart.find(id);
// inside cart.products
[{productId: 'asvhbajAS13', quantity: 8 },{productId: 'asvhbajAS13', quantity: 2 }]
之后我想修改所有产品,这种方法对吗?
我试过的:
Product.find({
'_id': { $in: { cart.products } }
}, function(err, product) {
})
});
解决方案
您的代码是正确的,但如果您使用 findOne() 。或者您可以再次使用填充而不是查询:
cart = Cart.find(id).populate("products")
推荐阅读
- nlp - 云 TPU 上的 Flair NLP 包
- python - 无法理解以下熊猫代码
- r - 按周统计活跃的观察
- javascript - 网格中的可排序 jquery 矩形(相对尺寸)
- swift - RxSwift 重新加载动画中的 RxDatasource 不更新数据源
- python-3.x - QTreeWidget 和 QPainter 组合
- macos - 如何在 MacOS 上安装 lua 开发库?
- python - Python中的采访数据:计算由说话者分隔的某个共现
- batch-file - 为什么由于一些奇怪的字符编码问题而无法处理来自文本文件的 wmic 数据?
- ruby-on-rails-5 - Rails 5 Active Storage 回形针式缩略图表单预览