使用猫鼬更新或删除子文档

时间:2020-09-09 11:19:32

标签: mongodb mongoose

这是我的代码,用于从一组嵌套文档中更新产品。 效果很好,但我认为我做得不好。还有其他更新方式

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');
        }

1 个答案:

答案 0 :(得分:0)

这是一种更清洁的方法:

await this.categoryService.update({
  _id: category_id
}, {
  $pull: {
    products: product._id
  }
})

或者,如果要在更新后返回对象,则可以将findOneAndUpdate{new: true}优化一起使用。

$pull运算符从数组中删除一个元素。

更新

如果要更新嵌套文档,可以使用$arrayFilter

例如,如果您要更新特定的产品名称。我想您有特定的product_id

await this.categoryService.update({
  _id: category_id
}, {
  $set: {
    'products.$[elem].name': newProductName
  }
}, {
  arrayFilters: [{'elem._id': product_id}]
});