提问者:小点点

猫鼬更新子阵列项


我正在尝试更新集合中的子数组项,我正在尝试使用set,但无法使用_id使其工作,只有当我说array[0].。。

下面是我的方法:

    exports.updateSubCategory = (req, res) => {
      const category = req.category;
      Category.findById(category._id, function (err, doc) {
        if (err) {
         
            return res.status(400).json({
              error: "Can't Find parent category",
            });
          
        } else {
           doc.subcategory.set(0, { name: req.body.name }); works
           doc.subcategory.set(req.body.id, { name: req.body.name });//doesn't work
           doc.subcategory.set({_id:req.body.id}, { name: req.body.name });//doesn't work
          doc.save((err, updatedCategory) => {
            if (err) {
              return res.status(400).json({
                error: "Can't update  subcategory",
              });
            }
            res.json(updatedCategory);
          });
        }
      });
    };

我的架构:

const mongoose = require("mongoose");

const categorySchema = new mongoose.Schema(
  {
    name: {
      type: String,
      trim: true,
      required: true,
      maxlength: 32,
      unique: true,
    },
    subcategory: [
      {
        name: {
          type: String,
          trim: true,
          required: true,
          maxlength: 32,
          unique: true,
        },
      },
    ],
  },
  { timestamps: true }
);

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

共1个答案

匿名用户

解决方案:

exports.updateSubCategory = (req, res) => {
      const category = req.category;
      Category.findById(category._id, function (err, doc) {
        if (err) {
         
            return res.status(400).json({
              error: "Can't Find parent category",
            });
          
        } else {
          let subdoc = doc.subcategory.id(req.body.id);
          subdoc.name = req.body.name;
          doc.save((err, updatedCategory) => {
            if (err) {
              return res.status(400).json({
                error: "Can't update  subcategory",
              });
            }
            res.json(updatedCategory);
          });
        }
      });
    };