猫鼬更新子数组项

时间:2020-07-20 13:20:10

标签: node.js mongodb mongoose

我正在尝试更新集合中的子数组项,我正在尝试使用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 个答案:

答案 0 :(得分: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 {
          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);
          });
        }
      });
    };