首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Mongoose更新或删除SubDocument

使用Mongoose更新或删除SubDocument
EN

Stack Overflow用户
提问于 2020-09-09 19:19:32
回答 1查看 15关注 0票数 0

下面是我的代码,我用它来更新嵌套文档数组中的Product。它工作得很好,但我认为我没有用更好的方法。有没有其他方法可以更新它?

代码语言:javascript
复制
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');
        }
EN

回答 1

Stack Overflow用户

发布于 2020-09-09 19:36:09

下面是一种更简洁的方法:

代码语言:javascript
复制
await this.categoryService.update({
  _id: category_id
}, {
  $pull: {
    products: product._id
  }
})

或者,如果你想在更新后返回对象,你可以使用带有{new: true}选项的findOneAndUpdate

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

更新

如果你想更新一个嵌套的文档,你可以使用$arrayFilter

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

代码语言:javascript
复制
await this.categoryService.update({
  _id: category_id
}, {
  $set: {
    'products.$[elem].name': newProductName
  }
}, {
  arrayFilters: [{'elem._id': product_id}]
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63810572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档