下面是我的代码,我用它来更新嵌套文档数组中的Product。它工作得很好,但我认为我没有用更好的方法。有没有其他方法可以更新它?
async updateProduct(parent: any, args: any, context: any) {
const { category_id, product } = args;
const category = await this.categoryService.findById( category_id );
const idx = category.products.findIndex( _product => _product._id.toString() === product._id );
if( idx >= 0 ) {
delete product._id;
const p = JSON.parse( JSON.stringify( category.products[ idx ] ));
category.products[ idx ] = { ...p, ...product};
return category.save();
}
throw new NotFoundException('Product Not found');
}发布于 2020-09-09 19:36:09
下面是一种更简洁的方法:
await this.categoryService.update({
_id: category_id
}, {
$pull: {
products: product._id
}
})或者,如果你想在更新后返回对象,你可以使用带有{new: true}选项的findOneAndUpdate。
$pull运算符从数组中删除一个元素。
更新
如果你想更新一个嵌套的文档,你可以使用$arrayFilter。
例如,如果您想要更新特定的产品名称。我假设您有自己特定的product_id。
await this.categoryService.update({
_id: category_id
}, {
$set: {
'products.$[elem].name': newProductName
}
}, {
arrayFilters: [{'elem._id': product_id}]
});https://stackoverflow.com/questions/63810572
复制相似问题