簡體   English   中英

Mongoose 更新子數組項

[英]Mongoose update subarray item

我正在嘗試更新我的集合中的子數組項,我正在嘗試使用 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);

解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM