首页 > 解决方案 > NodeJs Mongoose 更新分类产品

问题描述

我有类别 mongoose 文档,我想更新他的产品。每次更新产品时只需重写它们,我只有最后一次放置记录。如何填充产品?

const category = new mongoose.Schema({
  
  products: [{ type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
  
});

    module.exports = mongoose.model("Category", category);

    exports.updateCategory = catchAsyncErrors(async (req, res, next) => {
  let category = await Category.findById(req.params.id);


  category = await Category.findByIdAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true,
    useFindAndModify: false,
  })

  res.send(200).json({
    success: true,
    category
  });
});

标签: node.jsmongodbmongoose

解决方案


假设您的产品在正文中称为产品:

category = await Category.findByIdAndUpdate(req.params.id, { $push: { products: req.body.products } }, {
  new: true,
  runValidators: true,
  useFindAndModify: false,
})

推荐阅读