提问者:小点点

NodeJs Mongoose更新类别产品


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

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

共1个答案

匿名用户

假设您的产品被称为Body中的产品:

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