【问题标题】:Push data inside specific field在特定字段内推送数据
【发布时间】:2021-05-11 07:54:30
【问题描述】:

谁能告诉我如何在组内推送数据?

产品架构

    const productSchema = new mongoose.Schema({
    name:{
        type:String
    },
    user:[{ 
        author:{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'user'
        }
    }],
    group:[{
        group:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'group',
        item:{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'item',
        }
    }
    }],
    price:{
        type:number
    },

});

productSchema.pre<IProduct>(/^find/, function(next) {
    this.populate({
          path: 'user.author',
          select: 'fullName email'
        });
        next();
      });

productSchema.pre<IProductSchema>(/^find/, function(next) {
    this.populate({
        path: 'group.group',
        select: '-__v'
        })
        next();
    });
 productSchema.pre<IProductSchema>(/^find/, function(next) {
        this.populate({
            path: 'group.group.item',
            select: '-__v -group'
        })
            next();
});

我成功填充了 group.group 但在 group.group.item 我无法推送数据,这是我的推送代码。

        const updateProduct = await PRODUCT.findByIdAndUpdate(req.params.id,  {
        $push: {
          group: { group: req.params.groupId}
        }
        }
    );
    const query = await Item.find().where(`group`).equals(req.params.groupId).select('-group id');
 query.forEach(async element => {
        const updateProduct = await PRODUCT.findByIdAndUpdate(req.params.id,  {
            $push: {
                group: {"group.item": 'element._id'}}
            }
            
        );
    });

我花了最后几个小时试图找到解决方案,但不幸的是我无法找到它。希望有人能帮助我。

祝你有美好的一天!

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    基于$pushdocumentation

    $push 运算符将指定的值附加到数组中

    在模式项中是一个对象,如果你想推送一个值,试试这样

    item:[{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'item',
    }]
    

    如果您不想根据以下代码将项目的类型更改为array,请找到带有_idgroup._id 的文档,然后像这样更新项目

    await PRODUCT.findOneAndUpdate(
      {
        _id: req.params.id,
        'group._id': groupId,
      },
      {
        "group.$.item" : "the ID"
      }
    );
    

    如果你改变了项目的类型

    await PRODUCT.findOneAndUpdate(
      {
        _id: req.params.id,
        'group._id': groupId,
      },
      {$push:{
        "group.$.item" : element._id
      }}
    );
    

    【讨论】:

    • 我更改了架构但仍然无法推送它
    • 要推入父组吗??
    • 是的,这就是我想要的
    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多